SpringMVC归纳-2(Session会话、拦截器)
要点:
1.HttpSession:一个session的建立是从一个用户向服务器发第一个请求开始,而以用户显式结束或session超时为结束,借助session能在一定时间内记录用户状态。
2.ModelAndView:既可以设置URL地址,又可以渲染视图。
3.HandlerInterceptor:拦截器接口,通过实现改接口的三个方法(preHandle、postHandle、afterCompletion)可以自定义一个拦截器。
实例:
实现登录、购物车功能。
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>乐淘登录</title> </head> <body> <form action="http://localhost:8888/login-commit" method="post"> <input type="submit" value="login"> </form> </body> </html>
mall.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>乐淘商场</title> </head> <body> <form action="http://localhost:8888/shopcar" method="POST"> <label>请选择要购买的书籍:<br> <input type="checkbox" name="bookname" value="C Prime Plus">C Prime Plus<br> <input type="checkbox" name="bookname" value="C Prime Plus2">C Prime Plus2<br> <input type="checkbox" name="bookname" value="C Prime Plus3">C Prime Plus3<br> <input type="checkbox" name="bookname" value="C Prime Plus4">C Prime Plus4<br> </label> <input type="submit" value="加入购物车"> </form> <form action="http://localhost:8888/quit" method="POST"> <input value="log out" type="submit"> </form> </body> </html>
myshoppingcar.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>乐淘购物车</title> </head> <body> <h2>我的购物车:</h2> <!--存在购买时显示已购书籍--> <ul th:if="${books.size()} != 0"> <li th:each="bookcount:${books}" th:text="${bookcount}"></li> </ul> <!--无购买--> <div th:if="${books.size()} == 0"> 您未购买任何书籍! </div> <form action="http://localhost:8888/mall" method="GET"> <input type="submit" value="继续购买"> </form> </body> </html>
Books.java
package com.example.demo.controller.login; import java.util.HashMap; import java.util.Map.Entry; import java.util.Set; public class Books { private HashMap<String,Integer> books = new HashMap<String,Integer>(); //根据请求URL中获得的表单数组,更新已有书本 public void refreshBooks(String[] newbooks) { for (String book:newbooks) { if (books.containsKey(book)) { books.put(book, books.get(book)+1); }else { books.put(book, 1); } } } //获取books集合,送往页面 public Set<Entry<String, Integer>> getbooks(){ return books.entrySet(); } }
LoginController.java
package com.example.demo.controller.login; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; @Controller public class LoginController { //登录界面 @GetMapping("login") public String getLogin(HttpServletRequest req) { HttpSession session = req.getSession(); //已登录直接进入到商场 if (session.getAttribute("login")!=null) { return "redirect:mall"; } return "login"; } //登录请求处理 @PostMapping("login-commit") public String postLogin(HttpServletRequest req) { HttpSession session = req.getSession(); //session标记登录状态 session.setAttribute("login",true); return "redirect:mall"; } //退出登录,保留购物记录 @PostMapping("quit") public String quit(HttpServletRequest req) { HttpSession session = req.getSession(); session.removeAttribute("login"); return "redirect:login"; } }
ShoppingController.java
package com.example.demo.controller.login; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class ShoppingController { //商场 @GetMapping("mall") public String getMall() { return "mall"; } //我的购物车 @PostMapping("shopcar") public ModelAndView getShopCar(ModelAndView view,HttpServletRequest req) { HttpSession session = req.getSession(); Books books = (Books) session.getAttribute("shopcar");//session会话获取已购书籍 String[] newbooks = req.getParameterValues("bookname");//新的购物请求 //从未购买 if (books==null){ books = new Books(); } //刷新session会话 if (newbooks!=null) { books.refreshBooks(newbooks); session.setAttribute("shopcar", books); } //刷新model,渲染视图 view.addObject("books",books.getbooks()); view.setViewName("myshoppingcar"); return view; } }
LoginInterceptor.java
package com.example.demo.controller.login; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; //登录拦截器 public class LoginInterceptor implements HandlerInterceptor { @Override //在Controller方法之前调用 public boolean preHandle(HttpServletRequest req,HttpServletResponse res,Object handler) throws IOException { HttpSession session = req.getSession(); if (session.getAttribute("login") != null) { System.out.println("login!"); return true; } res.sendRedirect("login"); return false; } @Override public void postHandle(HttpServletRequest req,HttpServletResponse res,Object handler,ModelAndView modelandview) throws Exception { //Controller方法处理完,但html页面并未送出显示时调用 } @Override public void afterCompletion(HttpServletRequest req,HttpServletResponse res,Object handler,Exception ex) { //页面渲染完毕后调用,通常用来回收资源,类似于finally } }
SpringWebConfig.java
package com.example.demo.controller.login; import org.springframework.boot.SpringBootConfiguration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @SpringBootConfiguration public class SpringWebConfig implements WebMvcConfigurer{ //增加拦截器,可以对特定URL设定拦截以检查是否登录 public void addInterceptors(InterceptorRegistry registry) { //装载一个拦截器,可以使用通配符,或字符串数组 registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/mall","/quit"); } }