一、准备工作

参考springMVC入门一,搭建maven项目如下:

前台结构如下:

项目介绍:使用springMVC实现前后台数据交互,例如controller返回json,页面传入pojo

二、具体代码

controller类:HelloWorldController

  1. package com.cn.project.controller;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.ui.Model;
  7. import org.springframework.web.bind.annotation.RequestBody;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.ResponseBody;
  10. import com.cn.common.Result;
  11. import com.cn.project.entity.TProjectInfo;
  12.  
  13. @Controller
  14. public class HelloWorldController {
  15.  
  16. /**
  17. * 返回json
  18. * 1、@ResponseBody
  19. * 2、引入 jackson包
  20. * 3、配置spring json转换器、或者spring驱动注解 <mvc:annotation-driven/>
  21. * @param model
  22. * @return
  23. */
  24. @RequestMapping("/hello1") //访问http://localhost:8080/HelloSpringMVC/hello1
  25. @ResponseBody
  26. public List<TProjectInfo> query(Model model){
  27.  
  28. List<TProjectInfo> projectInfos = new ArrayList<TProjectInfo>();
  29. projectInfos.add(new TProjectInfo("1", "项目1"));
  30. projectInfos.add(new TProjectInfo("2", "项目2"));
  31. projectInfos.add(new TProjectInfo("3", "项目3"));
  32. projectInfos.add(new TProjectInfo("4", "项目4"));
  33. projectInfos.add(new TProjectInfo("5", "项目5"));
  34.  
  35. return projectInfos; //前台接收:response.data
  36. }
  37.  
  38. /**
  39. * 封装返回值与自定义状态码
  40. * @param model
  41. * @return
  42. */
  43. @RequestMapping("/hello2") //访问http://localhost:8080/HelloSpringMVC/hello2
  44. @ResponseBody
  45. public Result query2(Model model){
  46.  
  47. List<TProjectInfo> projectInfos = new ArrayList<TProjectInfo>();
  48. projectInfos.add(new TProjectInfo("1", "项目1"));
  49. projectInfos.add(new TProjectInfo("2", "项目2"));
  50. projectInfos.add(new TProjectInfo("3", "项目3"));
  51. projectInfos.add(new TProjectInfo("4", "项目4"));
  52. projectInfos.add(new TProjectInfo("5", "项目5"));
  53.  
  54. return Result.ok().put("data", projectInfos); //前台接收:response.data.data
  55. }
  56.  
  57. /**
  58. * 前台传入pojo
  59. * 传入的是pojo的json字符串
  60. * 如data : angular.toJson($scope.project)
  61. * data:'{"projectNo":"11","projectName":"22"}'
  62. * data:JSON.stringify($scope.project)
  63. * data:$scope.project
  64. *
  65. * 注意:@RequestBody json转pojo,pojo一定要有空的构造函数,否则,前台找不到路径
  66. * "Content-Type": "application/json; charset=UTF-8"
  67. * @param projectInfo
  68. * @return
  69. */
  70. @RequestMapping("/insert")
  71. @ResponseBody
  72. public void insert(@RequestBody TProjectInfo projectInfo){
  73.  
  74. System.out.println(projectInfo);
  75.  
  76. }
  77.  
  78. /**
  79. * 前台传入 json字符串
  80. * data:$.param({jsonStr:JSON.stringify($scope.project)}) //后台接收String jsonStr
  81. *
  82. * 注意:content-type:application/x-www-form-urlencoded
  83. *
  84. * @param jsonStr
  85. */
  86. @RequestMapping("/insert2")
  87. @ResponseBody
  88. public void insert2(String jsonStr){
  89.  
  90. System.out.println(jsonStr);
  91.  
  92. }
  93.  
  94. /**
  95. * 返回字符串
  96. * @param model
  97. * @return
  98. */
  99. @RequestMapping("/hello") //访问http://localhost:8080/HelloSpringMVC/hello
  100. public String hay(Model model){
  101. model.addAttribute("greeting","hello Spring MVC"); //jsp页面接收 ${greeting}
  102.  
  103. return "index"; //跳转到 index.html 页面需要遵循 spring视图配置
  104. }
  105. }

html页面:project.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <!-- 兼容edge页面 -->
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <title>Insert title here</title>
  7.  
  8. <link href="../css/bootstrap.min.css" rel="stylesheet">
  9.  
  10. </head>
  11. <body data-ng-app="projectApp" data-ng-controller="projectCtrl">
  12. <div class="container-fluid" ng-if="cx">
  13. <!-- 面包屑 -->
  14. <ol class="breadcrumb">
  15. <li><a href="#">Home</a></li>
  16. <li><a href="#">人员管理</a></li>
  17. <li class="active">人员查询</li>
  18. </ol>
  19. <!-- 查询条件 -->
  20. <form class="form-inline" role="form">
  21. <div class="form-group">
  22. <label for="" class="control-label">姓名:</label> <input type="text"
  23. class="form-control" id="" placeholder="" ng-model="usreName">
  24. </div>
  25. <div class="form-group">
  26. <label for="" class="control-label">身份证号:</label> <input type="text"
  27. class="form-control" id="" placeholder="" ng-model="passPort">
  28. </div>
  29. <div class="form-group">
  30. <button type="button" class="btn btn-success" ng-click="query()">查询</button>
  31. <button type="reset" class="btn btn-success" ng-click="reset()">重置</button>
  32. </div>
  33. <div class="form-group">
  34. <button type="button" class="btn btn-success" ng-click="add()">新增</button>
  35. </div>
  36. </form>
  37.  
  38. <!-- 查询结果 -->
  39. <div class="row-fluid">
  40. <div class="span12">
  41. <table class="table">
  42. <thead>
  43. <tr>
  44. <th>编号</th>
  45. <th>项目号</th>
  46. <th>项目名称</th>
  47. </tr>
  48. </thead>
  49. <tbody>
  50. <tr data-ng-repeat="x in dataItems" repeat-finish href="#">
  51. <td ng-bind="$index + 1"></td>
  52. <td>
  53. <div ng-bind=x.projectNo></div>
  54. </td>
  55. <td>
  56. <div ng-bind=x.projectName></div>
  57. </td>
  58. </tr>
  59. </tbody>
  60. </table>
  61. </div>
  62. </div>
  63. </div>
  64.  
  65. <!-- 编辑页 -->
  66. <div ng-if="xz">
  67. <form class="form-inline" role="form">
  68. <div class="form-group">
  69. <label for="" class="control-label">项目号:</label> <input type="text"
  70. class="form-control" id="" placeholder="" ng-model="project.projectNo">
  71. </div>
  72. <div class="form-group">
  73. <label for="" class="control-label">项目名称:</label> <input type="text"
  74. class="form-control" id="" placeholder="" ng-model="project.projectName">
  75. </div>
  76.  
  77. </form>
  78. <div>
  79. <div class="form-group">
  80. <button type="button" class="btn btn-success" ng-click="save()">保存</button>
  81. </div>
  82. </div>
  83. </div>
  84.  
  85. </body>
  86.  
  87. <script src="../js/lib/jquery.min.js"></script>
  88. <script src="../js/lib/bootstrap.min.js"></script>
  89. <script src="../js/lib/angular-1.3.1.min.js"></script>
  90.  
  91. <script>
  92. var app = angular.module('projectApp', []);
  93. app.controller('projectCtrl',function($scope,$http) {
  94.  
  95. //变量设置
  96. $scope.cx = true;
  97. $scope.project={}; //保证修改页面$scope.project能取到值
  98.  
  99. //查询方法
  100. $scope.query = function() {
  101. $http(
  102. {
  103. method : 'POST',
  104. headers : {
  105. "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" //或者application/json x-www-form-urlencoded
  106. },
  107. url : '../hello1',
  108. data :''
  109. })
  110. .then(
  111. function successCallback(response) {
  112. debugger;
  113. console.log(response);
  114. $scope.dataItems = response.data;
  115. },
  116. function errorCallback(response) {
  117. debugger;
  118. alert("查询失败");
  119. });
  120. }
  121.  
  122. $scope.add = function(){
  123. $scope.cx = false;
  124. $scope.xz = true;
  125. }
  126.  
  127. //保存方法
  128. $scope.save = function() {
  129. debugger;
  130. $http(
  131. {
  132. method : 'POST',
  133. headers : {
  134. "Content-Type": "application/json; charset=UTF-8" //或者application/json
  135. },
  136. url : '../insert',
  137. //data : angular.toJson($scope.project) //"{"projectNo":"11","projectName":"22"}"
  138. //data:'{"projectNo":"11","projectName":"22"}'
  139. //data:$.param({jsonStr:JSON.stringify($scope.project)}) //后台接收String jsonStr,注意:content-type:application/x-www-form-urlencoded
  140. //data:JSON.stringify($scope.project), //"{"projectNo":"11","projectName":"22"}"
  141. data:$scope.project
  142. })
  143. .then(
  144. function successCallback(response) {
  145. debugger;
  146. alert("新增成功");
  147. },
  148. function errorCallback(response) {
  149. debugger;
  150. alert("新增失败");
  151. });
  152. }
  153.  
  154. });
  155. </script>
  156.  
  157. </html>

springMVC配置:spring-mvc-servlet.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context-4.1.xsd
  10. http://www.springframework.org/schema/mvc
  11. http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
  12.  
  13. <!-- 自动扫描注解 -->
  14. <context:component-scan base-package="com.cn"/>
  15.  
  16. <!--
  17. 处理静态资源,如img等,这类资源不通过DispatcherServlet转发,由容器自己处理
  18. <mvc:default-servlet-handler default-servlet-name="所使用的Web服务器默认使用的Servlet名称" />
  19.  
  20. 对静态资源文件的访问
  21. <mvc:resources mapping="/img/**" location="/img/" />
  22. -->
  23. <mvc:default-servlet-handler />
  24. <!-- <mvc:resources /> -->
  25.  
  26. <!--
  27. 使用注解时需要配置这个,springMVC为@Controller分发请求所必须的
  28. -->
  29. <mvc:annotation-driven/>
  30.  
  31. <!-- <mvc:annotation-driven /> 该配置会默认注入以下两个bean,如果需要对以下bean进行修改,需要显示的注入这两个bean -->
  32. <!-- <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> -->
  33. <!-- spring MVC提供的适配器 spring默认加载 (如果不修改默认加载的4类转换器,该bean可不配置)-->
  34. <!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  35. <property name="messageConverters">
  36. 该适配器默认加载以下4类转换器,spring提供了很多转换器
  37. <list>
  38. <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter" />
  39. <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
  40. <bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter" />
  41. <bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter" />
  42. 前台json传后台,否则报415
  43. <bean class="org.springframework.http.converter.StringHttpMessageConverter" />
  44. controller返回json
  45. <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
  46. <property name="supportedMediaTypes">
  47. <list>
  48. <value>application/json;charset=UTF-8</value>
  49. </list>
  50. </property>
  51. </bean>
  52. </list>
  53. </property>
  54. </bean> -->
  55.  
  56. <!--
  57. 视图控制器:
  58. 如果返回的是视图逻辑名称,如success,那么视图解析器就必须配置
  59. 如果返回的是真实视图名称,如/index.jsp,那么视图解析器为可选配置
  60. -->
  61. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  62. <property name="prefix" value="/html/" /> <!-- 前缀 -->
  63. <property name="suffix" value=".html" /> <!-- 后缀 -->
  64. </bean>
  65. </beans>

web.xml配置:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  5. http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID">
  6.  
  7. <display-name>HelloSpringMVC</display-name>
  8.  
  9. <servlet>
  10. <!-- 加载springmvc配置: 1、这里的servlet-name默认指向“spring-mvc-servlet.xml” 2、手动指定:<init-param> -->
  11. <servlet-name>spring-mvc</servlet-name>
  12. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  13.  
  14. <!-- <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc-servlet.xml</param-value>
  15. </init-param> -->
  16.  
  17. <!-- <load-on-startup>:容器启动时,加载这个servlet的顺序 取值:0,1,2,3... 数字越小,越先加载 -->
  18.  
  19. <load-on-startup>1</load-on-startup>
  20. </servlet>
  21.  
  22. <!-- url-pattern:servlet访问地址url配置 /* path.endsWith("/*") *. path.starsWith("*.")
  23. / path.equals("/") 其他 -->
  24. <servlet-mapping>
  25. <servlet-name>spring-mvc</servlet-name>
  26. <url-pattern>/</url-pattern>
  27. </servlet-mapping>
  28.  
  29. <!-- 加载其他的xml配置 -->
  30. <context-param>
  31. <param-name>contextConfigLocation</param-name>
  32. <param-value>/WEB-INF/root-context.xml</param-value>
  33. </context-param>
  34.  
  35. <!-- Spring 监听器 -->
  36. <listener>
  37. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  38. </listener>
  39.  
  40. <!-- 页面编码设置 -->
  41. <filter>
  42. <filter-name>encodingFilter</filter-name>
  43. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  44. <init-param>
  45. <param-name>encoding</param-name>
  46. <param-value>UTF-8</param-value>
  47. </init-param>
  48. <init-param>
  49. <param-name>forceEncoding</param-name>
  50. <param-value>true</param-value>
  51. </init-param>
  52. </filter>
  53. <filter-mapping>
  54. <filter-name>encodingFilter</filter-name>
  55. <url-pattern>/*</url-pattern>
  56. </filter-mapping>
  57. <welcome-file-list>
  58. <welcome-file>index.html</welcome-file>
  59. <welcome-file>index.htm</welcome-file>
  60. <welcome-file>index.jsp</welcome-file>
  61. <welcome-file>default.html</welcome-file>
  62. <welcome-file>default.htm</welcome-file>
  63. <welcome-file>default.jsp</welcome-file>
  64. </welcome-file-list>
  65.  
  66. </web-app>

controller返回封装类:Result.java

  1. package com.cn.common;
  2.  
  3. import java.util.HashMap;
  4. import java.util.Map;
  5.  
  6. /**
  7. * 返回数据封装类
  8. *
  9. */
  10. public class Result extends HashMap<String, Object> {
  11. private static final long serialVersionUID = 1L;
  12.  
  13. public Result() {
  14. this.put("code", 0);
  15. }
  16.  
  17. public static Result error() {
  18. return error(500, "未知异常,请联系管理员");
  19. }
  20.  
  21. public static Result error(String msg) {
  22. return error(500, msg);
  23. }
  24.  
  25. public static Result error(int code, String msg) {
  26. Result r = new Result();
  27. r.put("code", code);
  28. r.put("msg", msg);
  29. return r;
  30. }
  31.  
  32. public static Result ok(String msg) {
  33. Result r = new Result();
  34. r.put("msg", msg);
  35. return r;
  36. }
  37.  
  38. public static Result ok(Map<String, Object> map) {
  39. Result r = new Result();
  40. r.putAll(map);
  41. return r;
  42. }
  43.  
  44. public static Result ok() {
  45. return new Result();
  46. }
  47.  
  48. public Result put(String key, Object value) {
  49. super.put(key, value);
  50. return this;
  51. }
  52. }

三、页面访问

springMVC入门二的更多相关文章

  1. SpringMVC入门二: 1规范结构, 2简单整合MyBatis

    昨天拿springMVC写的helloworld结构不好, 这次先调整一下体系结构 , 然后简单整合一下MyBatis spring的配置还是以注解为主, 不过MyBatis的映射文件什么的还是拿xm ...

  2. springMvc 入门二

    目的:请求参数接受,输出,常见的注解(在上一篇入门1基础上) 1:请求参数的绑定 1.1绑定的机制 表单中请求参数都是基于key=value的. SpringMVC绑定请求参数的过程是通过把表单提交请 ...

  3. SpringMVC入门二:SSM整合(spring+springmvc+mybatis)

    一.编程步骤 1.引入依赖 spring.springmvc.mybatis.mybatis-spring.mysql.druid.log4j.servlet-api.jstl.fastjson 2. ...

  4. SpringMvc入门二----HelloWorld

    1. 导入需要的架包: 2. 配置web.xml,添加Servlet <servlet> <servlet-name>springmvc</servlet-name> ...

  5. <SpringMvc>入门二 常用注解

    1.@RequestMapping @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME ...

  6. Spring+SpringMVC+MyBatis深入学习及搭建(十二)——SpringMVC入门程序(一)

    转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/6999743.html 前面讲到:Spring+SpringMVC+MyBatis深入学习及搭建(十一)——S ...

  7. SpringMVC入门学习(二)

    SpringMVC入门学习(二) ssm框架 springMVC  在上一篇博客中,我简单介绍了一下SpringMVC的环境配置,和简单的使用,今天我们将进一步的学习下Springmvc的操作. mo ...

  8. SpringMVC.入门篇《二》form表单

    SpringMVC.入门篇<二>form表单 项目工程结构: 在<springmvc入门篇一.HelloWorld>基础上继续添加代码,新增:FormController.ja ...

  9. Java开发学习(二十三)----SpringMVC入门案例、工作流程解析及设置bean加载控制

    一.SpringMVC概述 SpringMVC是隶属于Spring框架的一部分,主要是用来进行Web开发,是对Servlet进行了封装.SpringMVC是处于Web层的框架,所以其主要的作用就是用来 ...

随机推荐

  1. 实现Callable的对象中,用@Autowired注入别的对象失败

    场景是这样: 我需要在一个实现类A中写一个拿到返回值的多线程,于是用的Callable,在这个实现类A外我又写了一个专门实现Callable的实现类B,在B中用spring注解@Autowired注入 ...

  2. 用 React 编写的基于Taro + Dva构建的适配不同端(微信小程序、H5、React-Native 等)的时装衣橱

    前言 Taro 是一套遵循 React 语法规范的 多端开发 解决方案.现如今市面上端的形态多种多样,Web.React-Native.微信小程序等各种端大行其道,当业务要求同时在不同的端都要求有所表 ...

  3. Angular搭建脚手架

    1.安装CLI: cnpm install -g @angular/cli //卸载: npm uninstall -g @angular/cli   npm cache clean 2.检测是否成功 ...

  4. #include stdio.h(7)

    #include <stdio.h> int main() { //***********一.循环语句*************** //什么叫做循环: //重复的做某件事情,重复的执行一 ...

  5. Swift中as as! as?的区别

     as  :类型一致或者子类 仅当一个值的类型在运行时(runtime)和as模式右边的指定类型一致 - 或者是该类型的子类 - 的情况下,才会匹配这个值.如果匹配成功,被匹配的值的类型被转换成as模 ...

  6. DB2安装教程图解

    下载好之后,是exe文件,但是双击后基本上都是解压,但是使用自身的解压的话会有很多文件解压失败的情况,所以推荐使用自己电脑上自带的解压工具直接解压(如360解压,好压等). 解压之后直接运行setup ...

  7. 光标显示样式 css 中 cursor 属性使用

    记录一下 cursor 的各种样式,方便自己查找.之前用到不常用的每次去 百度 或 Google 找不如自己记录下好找些. cursor光标类型 auto default none context-m ...

  8. JavaScript 常用的Math对象

    Math.ceil(x); //返回x向上取整后的整数值. Math.floor(x); //返回x向下取整后的整数值.. Math.round(x); //返回四舍五入后的整数. Math.abs( ...

  9. jquery对checkbox的操作汇总

    1.全选 $("#btn1").click(function(){ $("input[name='checkbox']").attr("checked ...

  10. 查看Linux网卡地址,网络地址

    查看网络地址 ip a 或ip addr show 或ifconfig,此指令在部分linux系统中不支持