SpringMVC拦截器(实现登录验证拦截器)

 

   本例实现登陆时的验证拦截,采用SpringMVC拦截器来实现

 

   当用户点击到网站主页时要进行拦截,用户登录了才能进入网站主页,否则进入登陆页面

 

  核心代码

  首先是index.jsp,显示链接

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>首页</title>
13     <meta http-equiv="pragma" content="no-cache">
14     <meta http-equiv="cache-control" content="no-cache">
15     <meta http-equiv="expires" content="0">    
16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
17     <meta http-equiv="description" content="This is my page">
18     <!--
19     <link rel="stylesheet" type="text/css" href="styles.css">
20     -->
21   </head>
22   
23   <body>
24      <div style="margin:0 auto;padding-top:100px;font-size:18px;" align="center">
25          <p><a href="loginpage.html">登陆</a></p>
26          <p><a href="user/home.html">用户中心</a></p>
27          <p><a href="exception.html">触发异常</a></p>
28      </div>
29   </body>
30 </html>

 

controller类

 1 package com.jikexueyuan.demo.springmvc.lesson4.controller;
 2 
 3 import javax.annotation.Resource;
 4 import javax.servlet.http.HttpServletRequest;
 5 
 6 import org.springframework.stereotype.Controller;
 7 import org.springframework.web.bind.annotation.RequestMapping;
 8 import org.springframework.web.bind.annotation.RequestMethod;
 9 import org.springframework.web.bind.annotation.RequestParam;
10 
11 import com.jikexueyuan.demo.springmvc.lesson4.constant.Global;
12 import com.jikexueyuan.demo.springmvc.lesson4.exception.MyException;
13 import com.jikexueyuan.demo.springmvc.lesson4.model.User;
14 import com.jikexueyuan.demo.springmvc.lesson4.service.LoginService;
15 
16 /**
17  * 这个例子讲解了如何定义MVC三层注解,使用@Resource进行注入,以及使用@RequestMapping、@RequestParam 、@SessionAttributes
18  */
19 
20 @Controller
21 public class LoginController extends BaseController {
22 
23     @Resource
24     LoginService service;
25     
26     @Resource
27     HttpServletRequest request;
28     
29     @RequestMapping("/exception")
30     public void exception() throws MyException{
31         throw new MyException("测试springmvc中的异常捕获");
32     }
33     
34     @RequestMapping("/loginpage")
35     public String toLoginPage(){
36         return "/WEB-INF/jsp/login.jsp";
37     }
38     
39     @RequestMapping("/user/home")
40     public String toUserHome(){
41         return "/WEB-INF/jsp/userhome.jsp";
42     }
43     
44     @RequestMapping("/logout")
45     public String logout(){
46         request.getSession().removeAttribute(Global.USER_SESSION_KEY);
47         return "redirect:/";
48     }
49     
50     @RequestMapping(value = "/doLogin", method = RequestMethod.POST)
51     public String doLogin(@RequestParam String userName, @RequestParam String password){
52         
53         try {
54             User user = service.doLogin(userName, password);
55             request.getSession().setAttribute(Global.USER_SESSION_KEY, user);
56             return "redirect:/user/home.html";
57         } catch (Exception e) {
58             return "/WEB-INF/jsp/login.jsp";
59         }
60         
61     }
62     
63 }

 

当点击用户中心时,触发拦截,相关配置如下

在spring-mvc.xml中加上拦截配置,拦截所有URL中包含/user/的请求,当然请求用户中心时就会触发这个拦截器了

1     <mvc:interceptors>
2         <mvc:interceptor>
3             <!-- 拦截所有URL中包含/user/的请求 -->
4             <mvc:mapping path="/user/**"/>
5             <bean class="com.jikexueyuan.demo.springmvc.lesson4.interceptor.LoginInterceptor"></bean>
6         </mvc:interceptor>
7     </mvc:interceptors>

 

然后是bean指向的具体的interceptor类,如果session保存的用户信息为null,则跳到login页面,postHandle和afterCompletion方法都不执行,反之都执行。

 1 package com.jikexueyuan.demo.springmvc.lesson4.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.jikexueyuan.demo.springmvc.lesson4.constant.Global;
10 
11 public class LoginInterceptor implements HandlerInterceptor {
12 
13     @Override
14     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
15         Object user = request.getSession().getAttribute(Global.USER_SESSION_KEY);
16         if (user == null) {
17             System.out.println("尚未登录,调到登录页面");
18             response.sendRedirect("/loginpage.html");
19             return false;
20         }
21         
22         return true;
23     }
24 
25     @Override
26     public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
27         System.out.println("postHandle");
28     }
29 
30     @Override
31     public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
32         System.out.println("afterCompletion");
33     }
34 
35 }

至此,简单的springmvc拦截器就完成了。

 

posted @ 2016-08-16 22:54  UniqueColor  阅读(30339)  评论(2编辑  收藏  举报