SpringMVC 攔截器的使用示例
簡(jiǎn)介
SpringMVC的處理器攔截器類似于Servlet開發(fā)中的過濾器Filter,用于對(duì)處理器進(jìn)行預(yù)處理和后處理。開發(fā)者可以自己定義一些攔截器來實(shí)現(xiàn)特定的功能。
過濾器
- servlet規(guī)范中的一部分,任何java web工程都可以使用
- 在url-pattern中配置了/*之后,可以對(duì)所有要訪問的資源進(jìn)行攔截
攔截器
- 攔截器是SpringMVC框架自己的,只有使用了SpringMVC框架的工程才能使用
- 攔截器只會(huì)攔截訪問的控制器方法, 如果訪問的是jsp/html/css/image/js是不會(huì)進(jìn)行攔截的
過濾器與攔截器的區(qū)別:
攔截器是AOP思想的具體應(yīng)用。
攔截器初體驗(yàn)
1.新建一個(gè)項(xiàng)目,添加web支持,在IDEA導(dǎo)入該項(xiàng)目依賴的lib包。
2.配置web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <filter> <filter-name>encoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
3.配置springmvc-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 掃描指定包,讓指定包下的注解生效 --> <context:component-scan base-package="controller"/> <mvc:annotation-driven/> <!-- JSON解決亂碼--> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg value="UTF-8"/> </bean> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper"> <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"> <property name="failOnEmptyBeans" value="false"/> </bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 視圖解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
4.編寫自定義的攔截器。(實(shí)現(xiàn)HandlerInterceptor接口)
package 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 { //在請(qǐng)求處理的方法之前執(zhí)行 //如果返回true執(zhí)行下一個(gè)攔截器 //如果返回false就不執(zhí)行下一個(gè)攔截器 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("------------處理前------------"); return true; } //在請(qǐng)求處理方法執(zhí)行之后執(zhí)行 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("------------處理后------------"); } //在dispatcherServlet處理后執(zhí)行,做清理工作. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("------------清理------------"); } }
事實(shí)上,只要重寫preHandle方法就可以。
5.在springmvc-servlet.xml文件中配置攔截器
<!--關(guān)于攔截器的配置--> <mvc:interceptors> <mvc:interceptor> <!--/** 包括路徑及其子路徑--> <!--/admin/* 攔截的是/admin/add等等這種 , /admin/add/user不會(huì)被攔截--> <!--/admin/** 攔截的是/admin/下的所有--> <mvc:mapping path="/**"/> <!--bean配置的就是攔截器--> <bean class="interceptor.MyInterceptor"/> </mvc:interceptor> </mvc:interceptors>
6.編寫controller
package controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class InterceptorController { @RequestMapping("/interceptor") public String test(){ System.out.println("InterceptorController"); return "ok"; } }
7.配置Tomcat,進(jìn)行測(cè)試
初體驗(yàn):自定義攔截器實(shí)現(xiàn)了HandlerInterceptor接口,重寫了preHandle方法。在preHandle方法中,返回值決定了是否攔截,當(dāng)返回值為true時(shí),不攔截;反之則攔截。
8.結(jié)果:
- 返回值為true,攔截器不攔截,跳轉(zhuǎn)
- 返回值為false,攔截器攔截,不跳轉(zhuǎn)
攔截器再體驗(yàn)-登錄驗(yàn)證
實(shí)現(xiàn)思路
- 有一個(gè)登陸頁面,需要寫一個(gè)controller訪問頁面。
- 登陸頁面有一提交表單的動(dòng)作。需要在controller中處理。判斷用戶名密碼是否正確。如果正確,向session中寫入用戶信息。返回登陸成功。
- 攔截用戶請(qǐng)求,判斷用戶是否登陸。如果用戶已經(jīng)登陸。放行, 如果用戶未登陸,跳轉(zhuǎn)到登陸頁面
登錄界面
<%@ 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處理請(qǐng)求
package controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpSession; @Controller @RequestMapping("/user") public class UserController { //跳轉(zhuǎn)到登陸頁面 @RequestMapping("/jumplogin") public String jumpLogin() throws Exception { return "login"; } //跳轉(zhuǎn)到成功頁面 @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"; } }
登錄成功頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>登錄成功頁面</h1> <hr> ${user} <a href="${pageContext.request.contextPath}/user/logout">注銷</a> </body> </html>
index頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <h1>首頁</h1> <hr> <%--登錄--%> <a href="${pageContext.request.contextPath}/user/jumplogin">登錄</a> <a href="${pageContext.request.contextPath}/user/jumpSuccess">成功頁面</a> </body> </html>
index頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <h1>首頁</h1> <hr> <%--登錄--%> <a href="${pageContext.request.contextPath}/user/jumplogin">登錄</a> <a href="${pageContext.request.contextPath}/user/jumpSuccess">成功頁面</a> </body> </html>
編寫控制器
package interceptor; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class LoginInterceptor implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (request.getRequestURI().contains("login")) { return true; } HttpSession session = request.getSession(); // 如果用戶已登陸,不攔截 if(session.getAttribute("user") != null) { return true; } // 用戶沒有登陸,攔截,并跳轉(zhuǎn)到登陸頁面 request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response); return false; } }
在springmvc-servlet.xml配置攔截器
<mvc:interceptor> <mvc:mapping path="/**"/> <bean id="loginInterceptor" class="interceptor.LoginInterceptor"/> </mvc:interceptor>
配置Tomcat,測(cè)試。
結(jié)果:沒有登錄就無法直接訪問登陸成功頁面。
以上就是SpringMVC 中文亂碼的解決方案的詳細(xì)內(nèi)容,更多關(guān)于SpringMVC 中文亂碼的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
關(guān)于文件上傳MultipartBody的使用方法
這篇文章主要介紹了關(guān)于文件上傳MultipartBody的使用方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06Springboot 項(xiàng)目讀取Resources目錄下的文件(推薦)
這篇文章主要介紹了Springboot 項(xiàng)目讀取Resources目錄下的文件,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11詳解SpringBoot實(shí)現(xiàn)事件同步與異步監(jiān)聽
這篇文章主要通過示例為大家詳細(xì)介紹了SpringBoot中的事件的用法和原理以及如何實(shí)現(xiàn)事件同步與異步監(jiān)聽,快跟隨小編一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06Java中使用輾轉(zhuǎn)相除法求最大公約數(shù)
這篇文章主要介紹了Java中使用輾轉(zhuǎn)相除法求最大公約數(shù),本文直接給出代碼實(shí)例,需要的朋友可以參考下2015-05-05從try-with-resources到ThreadLocal,優(yōu)化你的代碼編寫方式
這篇文章主要為大家介紹了從try-with-resources到ThreadLocal,優(yōu)化代碼的編寫方式詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04SpringBoot+Redis執(zhí)行l(wèi)ua腳本的方法步驟
這篇文章主要介紹了SpringBoot+Redis執(zhí)行l(wèi)ua腳本的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11SpringBoot實(shí)現(xiàn)郵件發(fā)送功能的姿勢(shì)分享
我們?cè)谌粘i_發(fā)中,經(jīng)常會(huì)碰到email郵件發(fā)送的場(chǎng)景,如發(fā)送驗(yàn)證碼,向客戶發(fā)送郵件等等,這篇文章主要給大家介紹了關(guān)于SpringBoot實(shí)現(xiàn)郵件發(fā)送的相關(guān)資料,需要的朋友可以參考下2021-08-08