在pom文件中导入相关依赖:
<dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency>
建立用于测试的Controller:DataController
1 package com.yas.controller; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.ui.Model; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 import org.springframework.web.bind.annotation.SessionAttributes; 7 import org.springframework.web.bind.support.SessionStatus; 8 import org.springframework.web.servlet.ModelAndView; 9 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpSession; 12 13 @Controller 14 @RequestMapping("/data") 15 //SessionAttributes中包含的key,会从Model对象存入Session中 16 @SessionAttributes(value = {"city","street"}) 17 public class DataController { 18 19 //使用Request和Session 20 @RequestMapping("/test1") 21 public String test1(HttpServletRequest request, HttpSession session){ 22 request.setAttribute("name","张三"); 23 session.setAttribute("age",18); 24 25 return "data"; 26 } 27 28 @RequestMapping("/test2") 29 public String test2(Model model){ 30 model.addAttribute("gender",true); 31 32 model.addAttribute("city","北京"); 33 model.addAttribute("street","长安街"); 34 return "data2"; 35 } 36 37 @RequestMapping("/test3") 38 public String test4(SessionStatus sessionStatus){ 39 //清空session 40 sessionStatus.setComplete(); 41 return "data2"; 42 } 43 44 @RequestMapping("/test4") 45 public ModelAndView test4(){ 46 //ModelAndView 可以整合视图和对象 47 ModelAndView modelAndView = new ModelAndView(); 48 // modelAndView.setViewName("forward:/index.jsp"); 49 modelAndView.setViewName("hello"); 50 modelAndView.addObject("claz","001"); 51 return modelAndView; 52 } 53 54 }
用于测试的页面:
data.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> name:${requestScope.name} age:${sessionScope.age} </body> </html>
data2.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> gender:${requestScope.gender}<br> city:${sessionScope.city}<br> street:${sessionScope.street} </body> </html>
hello.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> hello jsp <br> claz:${requestScope.claz} </body> </html>