参数传递
ModelAndView传递
-
编写controller
@Controller @RequestMapping("/account") public class AccountController { //也可以不创建ModelAndView,直接在参数中指定@RequestMapping(value = "/findAccount9")public ModelAndView findAccount9(ModelAndView mv) {mv.addObject("msg", "欢迎你 springmvc");mv.setViewName("success");return mv;} }
-
在index.jsp里面定义超链接
<a href="/account/findAccount9">ModelAndView参数传递</a>
Model传递
-
编写controller
@Controller @RequestMapping("/account") public class AccountController { @RequestMapping(value = "/findAccount10")public String findAccount10(Model model) {model.addAttribute("msg", "欢迎你 springmvc");return "success";} }
-
在index.jsp里面定义超链接
<a href="/account/findAccount10">Model参数传递</a>
ServletAPI传递
-
编写controller
@Controller @RequestMapping("/account") public class AccountController { @RequestMapping("/findAccount11")public String findAccount11(HttpServletRequest request, HttpServletResponse response){request.setAttribute("msg","欢迎你 springmvc");return "success";} }
-
在index.jsp里面定义超链接
<a href="/account/findAccount11">ServletAPI传递</a>
JSON数据处理
添加json依赖
springmvc 默认使用jackson作为json类库,不需要修改applicationContext-servlet.xml任何配置,只需引入以下类库springmvc就可以处理json数据:
<!--spring-json依赖--> <dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.0</version> </dependency>
注解
-
@RequestBody:作用是接收前端ajax传递给后端的json字符串,并将json格式的数据转为java对象
-
@ResponseBody:作用是将java对象转为json格式的数据传递给前台ajax
案例
-
编写controller
@Controller @RequestMapping("/account") public class AccountController { @RequestMapping("/saveAccount2")@ResponseBodypublic Map saveAccount2(@RequestBody Account account){Map<String, Object> map = new HashMap<String, Object>();map.put("status",200);map.put("msg",account);return map;} }
-
在index.jsp里面定义ajax请求
-
添加按钮
<input type="button" value="测试ajax请求json和响应json" id="testJson"/>
-
引入js库文件
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
-
编写ajax代码
<script type="text/javascript">$(function(){$("#testJson").click(function(){$.ajax({type:"post",url:"/account/saveAccount2",contentType:"application/json;charset=UTF-8",data:'{"id":1,"name":"张二狗","money":999.0}',success:function(data){if(data.status == 200){alert(data.msg.name);alert(data.msg.money);}}})});})</script>
-
-
测试