五、传值
1. request和response对象是由服务器创建的。我们来使用它们
2. request对象是来获取请求消息,response对象是来设置响应消息
C得到数据后,跳转到V,并向V传递数据。进而V中可以渲染数据,让用户看到含有数据的页面
转发跳转:Request作用域
重定向跳转:Session作用域
5.1 Request和Session
//形参中 即可获得 request 和 session对象
@RequestMapping("/test1")
public String test1(HttpServletRequest request, HttpSession session){
System.out.println("test1");
request.setAttribute("name","张三");
session.setAttribute("age",18);
return "data";
}
在request和session中存入值
data.jsp
name: ${requestScope.name} <br>
age: ${sessionScope.age} <br>
5.2 JSP中取值
建议:重点复习 EL JSTL
//jsp中用EL表达式 取值即可
<fmt:formatDate value="${sessionScope.user.birth}" pattern="yyyy-MM-dd"/> <br/>
${sessionScope.user.birth} <br>
${requestScope.age}
5.3 Model
springmvc常用方法 重点。
//model中的数据,会在V渲染之前,将数据复制一份给request
@RequestMapping("/test2")
public String test2(Model model){
//model.addAttribute("gender",true);
model.addAttribute("city","北京");
model.addAttribute("street","长安街");
return "data2";
}
//jsp中用EL表达式 取值即可
<%--gender: ${requestScope.gender}--%>
city: ${sessionScope.city} <br>
street: ${sessionScope.street}
使用model.addAttribute( ,);方法存入值。 model会存一分在request中
如果想存在session中那就要在类上面添加注解@SessionAttributes(names = {“city”,“street”})
names后面存入k值
@RequestMapping("/test2")
public String test2(Model model){
model.addAttribute("city","北京");
model.addAttribute("street","长安街");
return "data2";
}
补:
// 清空所有 通过model存入session
@RequestMapping("/test3")
public String test3(SessionStatus status){
// 清空所有 通过model存入session
status.setComplete();
return "data2";
}
5.4 ModelAndView
//modelandview 可以集中管理 跳转和数据
@RequestMapping("/test4")
public ModelAndView testData(){//返回值类型为ModelAndView
//新建ModelAndView对象
ModelAndView modelAndView = new ModelAndView();
// 设置视图名,即如何跳转
modelAndView.setViewName("forward:/hello.jsp");
// 增加数据
modelAndView.addObject("claz","001");
return modelAndView;
}
//jsp中用EL表达式 取值即可
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
hello world <br>
claz: ${requestScope.claz}
</body>
</html>
5.5 @SessionAttributes–配合model使用
@SessionAttributes({“gender”,“name”}) :model中的 name和gender 会存入session中
SessionStatus 移除session
@Controller
@SessionAttributes({"gender","name"}) // model中的 name和gender 会存入session中
public class UserController {
@RequestMapping("/hello")
public String hello(Model m){
m.addAttribute("gender",true); // 会存入session
mv.addObject("name","zhj"); // 会存入session
return "index";
}
@RequestMapping("/hello2")
public String hello(SessionStatus status){
// 移除通过SessionAttributes存入的session
status.setComplete();
return "index";
}
}