Java自学之SpringMVC:Session
学习目的:使用session记录访问/check的访问次数,并使用/clean重置访问次数。
Part 1
修改IndexController,映射/check到check方法。每次访问该方法,session的count加一。
package controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
//import org.springframework.web.servlet.mvc.Controller;
@Controller
public class IndexController{
@RequestMapping("/index")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mav = new ModelAndView("index");
mav.addObject("message", "Hello Spring MVC");
return mav;
}
@RequestMapping("/jump")
public ModelAndView jump(){
ModelAndView mav = new ModelAndView("redirect:/index");
return mav;
}
@RequestMapping("/check")
public ModelAndView check(HttpSession session){
Integer integer = (Integer) session.getAttribute("count");
if (integer == null) {
integer = 0;
}
integer ++;
session.setAttribute("count",integer);
ModelAndView mav = new ModelAndView("check");
return mav;
}
}
Part 2
在WEB-INF/page下新建check.jsp,获取并打印count在浏览器上。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
session中记录的访问次数:${count}
Part 3
部署运行项目,启动Tomcat,在浏览器访问http://localhost:8080/springMVC_war_exploded/check,每次刷新访问次数都加1。
Part 4
在IndexController中新增如下代码,使/clean映射到clean方法,每访问/clean时,将session的count重置,并重定向到/check。
@RequestMapping("/clean")
public ModelAndView clean(HttpSession session){
session.removeAttribute("count");
ModelAndView mav = new ModelAndView("redirect:/check");
return mav;
}
在Part 3的基础上,访问http://localhost:8080/springMVC_war_exploded/clean,成功清除数据,并重定向到/check。

浙公网安备 33010602011771号