Spring mvc攔截器實現原理解析
概述
SpringMVC的處理器攔截器類似于Servlet開發中的過濾器Filter,用于對處理器進行預處理和后處理。開發者可以自己定義一些攔截器來實現特定的功能。
過濾器與攔截器的區別:攔截器是AOP思想的具體應用。
過濾器
servlet規范中的一部分,任何java web工程都可以使用在url-pattern中配置了/*之后,可以對所有要訪問的資源進行攔截
攔截器
攔截器是SpringMVC框架自己的,只有使用了SpringMVC框架的工程才能使用 攔截器只會攔截訪問的控制器方法, 如果訪問的是jsp/html/css/image/js是不會進行攔截的自定義攔截器
那如何實現攔截器呢?
想要自定義攔截器,必須實現 HandlerInterceptor 接口。
新建一個Moudule , 添加web支持
配置web.xml 和 springmvc-servlet.xml 文件
編寫一個攔截器
package com.xiaohua.interceptor;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class MyInterceptor implements HandlerInterceptor { //在請求處理的方法之前執行 //如果返回true執行下一個攔截器 //如果返回false就不執行下一個攔截器 public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { System.out.println('------------處理前------------'); return true; } //在請求處理方法執行之后執行 public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { System.out.println('------------處理后------------'); } //在dispatcherServlet處理后執行,做清理工作. public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { System.out.println('------------清理------------'); }}
在springmvc的配置文件中配置攔截器
<!--關于攔截器的配置--><mvc:interceptors> <mvc:interceptor> <!--/** 包括路徑及其子路徑--> <!--/admin/* 攔截的是/admin/add等等這種 , /admin/add/user不會被攔截--> <!--/admin/** 攔截的是/admin/下的所有--> <mvc:mapping path='/**'/> <!--bean配置的就是攔截器--> <bean /> </mvc:interceptor></mvc:interceptors>
編寫一個Controller,接收請求
package com.xiaohua.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;//測試攔截器的控制器@Controllerpublic class InterceptorController { @RequestMapping('/interceptor') @ResponseBody public String testFunction() { System.out.println('控制器中的方法執行了'); return 'hello'; }}
前端 index.jsp
<a href='http://www.cgvv.com.cn/bcjs/${pageContext.request.contextPath}/interceptor' rel='external nofollow' >攔截器測試</a>
啟動tomcat 測試一下!
驗證用戶是否登陸(認證用戶)
實現思路
有一個登陸頁面,需要寫一個controller訪問頁面。
登陸頁面有一提交表單的動作。需要在controller中處理。判斷用戶名密碼是否正確。如果正確,向session中寫入用戶信息。返回登陸成功。
攔截用戶請求,判斷用戶是否登陸。如果用戶已經登陸。放行, 如果用戶未登陸,跳轉到登陸頁面
代碼編寫
編寫一個登陸頁面 login.jsp
<%@ page contentType='text/html;charset=UTF-8' language='java' %><html><head> <title>Title</title></head><h1>登錄頁面</h1><hr><body><form action='${pageContext.request.contextPath}/user/login'> 用戶名:<input type='text' name='username'> <br> 密碼: <input type='password' name='pwd'> <br> <input type='submit' value='提交'></form></body></html>
編寫一個Controller處理請求
package com.xiaohua.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import javax.servlet.http.HttpSession;@Controller@RequestMapping('/user')public class UserController { //跳轉到登陸頁面 @RequestMapping('/jumplogin') public String jumpLogin() throws Exception { return 'login'; } //跳轉到成功頁面 @RequestMapping('/jumpSuccess') public String jumpSuccess() throws Exception { return 'success'; } //登陸提交 @RequestMapping('/login') public String login(HttpSession session, String username, String pwd) throws Exception { // 向session記錄用戶身份信息 System.out.println('接收前端==='+username); session.setAttribute('user', username); return 'success'; } //退出登陸 @RequestMapping('logout') public String logout(HttpSession session) throws Exception { // session 過期 session.invalidate(); return 'login'; }}
編寫一個登陸成功的頁面 success.jsp
<%@ page contentType='text/html;charset=UTF-8' language='java' %><html><head> <title>Title</title></head><body><h1>登錄成功頁面</h1><hr>${user}<a href='http://www.cgvv.com.cn/bcjs/${pageContext.request.contextPath}/user/logout' rel='external nofollow' >注銷</a></body></html>
在 index 頁面上測試跳轉!啟動Tomcat 測試,未登錄也可以進入主頁!
<%@ page contentType='text/html;charset=UTF-8' language='java' %><html> <head> <title>$Title$</title> </head> <body> <h1>首頁</h1> <hr> <%--登錄--%> <a href='http://www.cgvv.com.cn/bcjs/${pageContext.request.contextPath}/user/jumplogin' rel='external nofollow' >登錄</a> <a href='http://www.cgvv.com.cn/bcjs/${pageContext.request.contextPath}/user/jumpSuccess' rel='external nofollow' >成功頁面</a> </body></html>
編寫用戶登錄攔截器
package com.xiaohua.interceptor;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import java.io.IOException;public class LoginInterceptor implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException { // 如果是登陸頁面則放行 System.out.println('uri: ' + request.getRequestURI()); if (request.getRequestURI().contains('login')) { return true; } HttpSession session = request.getSession(); // 如果用戶已登陸也放行 if(session.getAttribute('user') != null) { return true; } // 用戶沒有登陸跳轉到登陸頁面 request.getRequestDispatcher('/WEB-INF/jsp/login.jsp').forward(request, response); return false; } public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { }}
在Springmvc的配置文件中注冊攔截器
<!--關于攔截器的配置--><mvc:interceptors> <mvc:interceptor> <mvc:mapping path='/**'/> <bean /> </mvc:interceptor></mvc:interceptors>
再次重啟Tomcat測試!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
