springMVC中经过后端处理的封装数据,以便前端读取
方法一:Model (ModelMap )用户无需自己创建。一般来说,可以用model来接收各种类型的数据。
引用:https://blog.csdn.net/itbiggod/article/details/79685610
//传值方法一
@RequestMapping("listCategory2")
public String listCategory2(Model model) {
// 接收查询的信息
List<Category> cs2= categoryService.list();
// 封装了查询的数据
model.addAttribute("test", cs2);
//重要!!需要给出返回model跳转的路径
return "listCategory2";
}
<!-- 获取值的时候,对应的是addAttribute的第一个参数!取了个别名为c-->
<c:forEach items="${test }" var="c" varStatus="st">
<tr>
<td>${c.id}</td>
<td>${c.name}</td>
</tr>
</c:forEach>
方法二:ModelAndView ModelAndView的实例是需要我们手动new的,只需要return 返回其对象即可。在jsp中:也是可以通过el表达式语言attributeName或者C标签库的attributeName或者C标签库的{name } 来获取并展示ModelAndView中的数据
modelAndView:
//传值方法二:使用ModelAndView
//当url处于这个时,由listCategory方法来处理请求
@RequestMapping("listCategory")
public ModelAndView listCategory(){
//创建一个模型视图对象
ModelAndView mav = new ModelAndView();
//获取到查询的数据
List<Category> cs= categoryService.list();
// //将数据放置到ModelAndView对象view中,第二个参数可以是任何java类型
mav.addObject("cs", cs);
// 放入jsp路径
mav.setViewName("listCategory");
//返回ModelAndView对象mav
return mav;
}
<!-- 获取值的时候,对应的是addAttribute的第一个参数!取了个别名为c-->
<c:forEach items="${test }" var="c" varStatus="st">
<tr>
<td>${c.id}</td>
<td>${c.name}</td>
</tr>
</c:forEach>
简单使用来说:model和modelAndView都是存储到前端读取信息的 map集合。只不过model不用自己创建,用来存放数据,不能设置页面跳转。
modelAndView需要自己创建并返回该对象,其中可以设置要跳转的页面。
。
。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
springMVC的重定向:return "redrect:页面路径"
请求的转发 // return "forward:/WEB-INF/pages/success.jsp";
/**
* 使用关键字的方式进行转发或者重定向
* @return
*/
@RequestMapping("/testForwardOrRedirect")
public String testForwardOrRedirect(){
System.out.println("testForwardOrRedirect方法执行了...");
// 请求的转发
// return "forward:/WEB-INF/pages/success.jsp";
// 重定向
return "redirect:/index.jsp";
}
。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
ajax
使用@RequestBody注解把json的字符串转换成JavaBean的对象
使用@ResponseBody注解把JavaBean对象转换成json字符串,直接响应
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="js/jquery.min.js"></script>
<script>
// 页面加载,绑定单击事件
$(function(){
$("#btn").click(function(){
// alert("hello btn");
// 发送ajax请求
$.ajax({
// 编写json格式,设置属性和值
url:"user/testAjax",
contentType:"application/json;charset=UTF-8",
data:'{"username":"发过去","password":"123","age":30}',
dataType:"json",
type:"post",
success:function(data){
// data服务器端响应的json的数据,进行解析
alert(data);
alert(data.username);
alert(data.password);
alert(data.age);
}
});
});
});
</script>
</head>
<body>
<button id="btn">发送ajax的请求</button>
</body>
</html>
@RequestMapping("/testAjax")
public @ResponseBody User testAjax(@RequestBody User user){
System.out.println("testAjax方法执行了...");
// 客户端发送ajax的请求,传的是json字符串,后端把json字符串封装到user对象中
System.out.println(user);
// 做响应,模拟查询数据库
user.setUsername("响应");
user.setAge(40);
// 做响应
return user;
}
}