SpringMVC拦截器

1、概述

SpringMVC中Interceptor的主要作用是拦截用户请求并进行相应的的处理。可以用拦截器进行用户权限验证,或者判定用户是否已经登陆。

拦截器的配置时可插拔式的设计。对于需要使用的拦截器,只需要在配置文件中进行配置。

2、HandlerInterceptor接口

自定义Interceptor拦截器类需要实现HandlerInterceptor接口或者继承抽象类HandlerInterceptorAdapter。

HandlerInterceptor拦截器接口中有三个方法。SpringMVC通过这三个方法来对用户请求进行拦截处理。

三个方法的使用参考AuthorizationInterceprot代码注释

3、拦截器权限验证

登录页面

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html>
 4 <html>
 5 <head>
 6 <meta charset="UTF-8">
 7 <title>登录页面</title>
 8 </head>
 9 <body>
10     <form action="login" method="post">
11         <!-- 提示信息 -->
12         <font color="red">${message }</font>
13         <table>
14             <tr>
15                 <td>用户名:</td>
16                 <td><input type="text" name="username" id="username"></td>
17             </tr>
18             <tr>
19                 <td>密码:</td>
20                 <td><input type="password" name="password" id="password"></td>
21             </tr>
22             <tr>
23                 <td><input type="submit" value="登录"></td>
24             </tr>
25         </table>
26     </form>
27 </body>
28 </html>

UserController

 1 package com.alphajuns.controller;
 2 
 3 import javax.servlet.http.HttpSession;
 4 
 5 import org.springframework.stereotype.Controller;
 6 import org.springframework.ui.Model;
 7 import org.springframework.web.bind.annotation.RequestMapping;
 8 import org.springframework.web.servlet.ModelAndView;
 9 
10 import com.alphajuns.domain.Customer;
11 
12 @Controller
13 public class UserController {
14 
15     @RequestMapping(value="/login")
16     public ModelAndView login(String username, String password,
17             ModelAndView mv, HttpSession session) {
18         // 模拟登录
19         if (username != null && username.equals("Test")
20                 && password != null && password.equals("123456")) {
21             // 将用户信息保存到session中
22             Customer c = new Customer();
23             c.setUsername(username);
24             c.setPassword(password);
25             session.setAttribute("customer", c);
26             // 转发到首页
27             mv.setViewName("redirect:main");
28         } else {
29             // 登录失败,给出提示信息,跳转到登录页面
30             mv.addObject("message", "用户名或密码错误,请重新登录!");
31             mv.setViewName("loginForm");
32         }
33         return mv;
34     }
35     
36 }

BookController

 1 package com.alphajuns.controller;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 import org.springframework.stereotype.Controller;
 7 import org.springframework.ui.Model;
 8 import org.springframework.web.bind.annotation.RequestMapping;
 9 
10 import com.alphajuns.domain.Book;
11 
12 @Controller
13 public class BookController {
14 
15     @RequestMapping(value="/main")
16     public String main(Model model) {
17         List<Book> book_list = new ArrayList<Book>();
18         book_list.add(new Book(1, "Spring实战", "Craig Walls"));
19         book_list.add(new Book(2, "疯狂Java讲义", "李刚"));
20         book_list.add(new Book(3, "并发编程实战", "Brian Goetz"));
21         book_list.add(new Book(4, "Java编程思想", "Bruce Eckel"));
22         model.addAttribute("book_list", book_list);
23         return "main";
24     }
25 }

main.jsp

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 4 <!DOCTYPE html>
 5 <html>
 6 <head>
 7 <meta charset="UTF-8">
 8 <title>首页</title>
 9 </head>
10 <body>
11     <h3>欢迎[${sessionScope.customer.username }]访问</h3>
12     <table border="1px" cellspacing="0" cellpadding="0">
13         <tr>
14             <td>序号</td><td>书名</td><td>作者</td>
15         </tr>
16         <c:forEach items="${requestScope.book_list }" var="book">
17             <tr>
18                 <td>${book.id }</td>
19                 <td>${book.name }</td>
20                 <td>${book.author }</td>
21             </tr>
22         </c:forEach>
23     </table>
24 </body>
25 </html>

AuthorizationInterceptor

 1 package com.alphajuns.interceptor;
 2 
 3 import javax.servlet.http.HttpServletRequest;
 4 import javax.servlet.http.HttpServletResponse;
 5 
 6 import org.springframework.web.servlet.HandlerInterceptor;
 7 import org.springframework.web.servlet.ModelAndView;
 8 
 9 import com.alphajuns.domain.Customer;
10 
11 public class AuthorizationIntercepor implements HandlerInterceptor {
12 
13     // 定义方形路径
14     private static final String[] IGNORE_URI = {"/loginForm", "/login"};
15     
16     /**
17      * 整个请求完之后执行,主要用于资源清理
18      */
19     @Override
20     public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
21             throws Exception {
22         System.out.println("AuthorizationInterceptor afterCompletion -->");
23     }
24 
25     /**
26      * Controller调用完之后,视图返回之前执行
27      */
28     @Override
29     public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
30             ModelAndView modelAndView) throws Exception {
31         System.out.println("AuthorizationInterceptor postHandle -->");
32     }
33 
34     /**
35      * Controller调用之前执行,返回true才能继续向下执行
36      */
37     @Override
38     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
39             throws Exception {
40         boolean flag = false;
41         // 获取请求的路径
42         String servletPath = request.getServletPath();
43         // 判断请求是否需要拦截
44         for (String s : IGNORE_URI) {
45             if (servletPath.contains(s)) {
46                 flag = true;
47                 break;
48             }
49         }
50         // 拦截请求
51         if (!flag) {
52             // 获取session中的用户
53             Customer c = (Customer) request.getSession().getAttribute("customer");
54             // 判断用户是否已登录
55             if (c == null) {
56                 // 用户未登录,设置提示信息,跳转至登录页面
57                 System.out.println("AuthorizationInceptor 拦截请求:");
58                 request.setAttribute("message", "请先登录再访问网站!");
59                 request.getRequestDispatcher("WEB-INF/jsp/loginForm.jsp").forward(request, response);
60             } else {
61                 System.out.println("AuthorizationInceptor 请求放行:");
62                 flag = true;
63             }
64         }
65         return flag;
66     }
67 
68     
69 }

配置拦截器

1     <!-- 配置拦截器 -->
2     <mvc:interceptors>
3         <mvc:interceptor>
4             <!-- 拦截所有请求 -->
5             <mvc:mapping path="/*"/>
6             <!-- 拦截器 -->
7             <bean class="com.alphajuns.interceptor.AuthorizationIntercepor"></bean>
8         </mvc:interceptor>
9     </mvc:interceptors>

 

posted @ 2019-06-22 13:32  AlphaJunS  阅读(189)  评论(0编辑  收藏  举报