SpringMVC07——响应数据
接下来看一下在SpringMVC中怎么去响应数据,就是怎么把controller中得到的数据传递到要跳转的jsp页面上去。
1.通过ModelAndView
public class HelloController {
@RequestMapping("/fun1")
public ModelAndView fun1() {
ModelAndView m=new ModelAndView();
m.addObject("msg", "modelandview msg...");
m.setViewName("index.jsp");
return m;
}
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>hello SpringMVC!</h1>
<h2>获取传递的信息:${msg} }</h2>
</body>
</html>
2.通过Map传值
@RequestMapping("/fun2")
public String fun2(Map<String, Object> m) {
System.out.println("-----------------");
m.put("msg", "map msg.....");
return "/index.jsp";
}
3.通过Model传值(最常用)
@RequestMapping("/fun3")
public String fun3(Model model) {
System.out.println("-----------------");
model.addAttribute("msg", "model msg......");
return "/index.jsp";
}
4.通过ModelMap传值
@RequestMapping("/fun4")
public String fun4(ModelMap mm) {
System.out.println("-----------------");
mm.addAttribute("msg", "modelmap");
return "/index.jsp";
}
5.传统的方式
//@RequestMapping("/fun5")
// public String fun5(HttpServletRequest req) {
//// req.setAttribute(name, o);
//// req.getSession();
//// req.getServletContext();
// }
那么写了这么多方式传值,到底是request作用域还是session作用域呢?下面来做一个验证
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>hello SpringMVC!</h1>
<h2>获取传递的信息:${msg} }</h2>
<h3>request:${requestScope.msg}</h3>
<h3>session:${sessionScope.msg}</h3>
<h3>application:${applicationScope.msg}</h3>
</body>
</html>
测试完之后发现数据都保存在request作用域中,就不一一截图了
那么如果想去session里面去取值,想放到session里面去怎么办?
可以添加注解@SessionAttributes(“msg”),这样的话request和session中都有了,至于application就没必要了,它是和应用生命周期绑定的,我们业务层面上不推荐往application里面放