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攔截器就完成了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM