Spring MVC-如何使用session
阿新 • • 發佈:2019-01-05
Session在使用者登入,一些特殊場合在頁面間傳遞資料的時候會經常用到
- 修改IndexController
對映 /check 到方法check()
為方法check()提供引數HttpSession session,這樣就可以在方法體中使用session了
接下來的邏輯就是每次訪問為session中的count+1.
最後跳轉到check.jsp頁面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; @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 i = (Integer) session.getAttribute("count"); if (i == null) i = 0; i++; session.setAttribute("count", i); ModelAndView mav = new ModelAndView("check"); return mav; } }
- check.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%> session中記錄的訪問次數:${count}
- 測試
訪問頁面
每次訪問,次數都+1http://127.0.0.1:8080/springmvc/check