您好,登錄后才能下訂單哦!
小編這次要給大家分享的是SpringBoot怎么配置攔截器,文章內(nèi)容豐富,感興趣的小伙伴可以來了解一下,希望大家閱讀完這篇文章之后能夠有所收獲。
步驟:
1.實現(xiàn)WebMvcConfigurer配置類
2.實現(xiàn)攔截器 3
. 把攔截器添加到配置中
4.添加需要攔截的請求
5.添加需要排除的請求
package com.zp.springbootdemo.interceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * 和springmvc的webmvc攔截配置一樣 * @author zp */ @Configuration public class WebConfigurer implements WebMvcConfigurer { /** * 攔截器配置 * @param registry */ @Override public void addInterceptors(InterceptorRegistry registry) { // addPathPatterns攔截所有請求,excludePathPatterns排除特殊的請求 //registry.addInterceptor(LoginInterceptor()).addPathPatterns("/**"); registry.addInterceptor(AuthorityInterceptor()).addPathPatterns("/**"); //excludePathPatterns 排除的請求 // registry.addInterceptor(LoginInterceptor()).addPathPatterns("/**").excludePathPatterns("/user/**"); // registry.addInterceptor(AuthorityInterceptor()).addPathPatterns("/**").excludePathPatterns("/user/**"); } /** * 攔截器一 * @return */ @Bean public LoginInterceptor LoginInterceptor() { return new LoginInterceptor(); } /** * 攔截器二 * @return */ @Bean public AuthorityInterceptor AuthorityInterceptor() { return new AuthorityInterceptor(); } }
基于URL實現(xiàn)的攔截器:
package com.zp.springbootdemo.interceptor; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginInterceptor extends HandlerInterceptorAdapter { /** * 在請求處理之前進行調(diào)用(Controller方法調(diào)用之前) * 基于URL實現(xiàn)的攔截器 * @param request * @param response * @param handler * @return * @throws Exception */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String path = request.getServletPath(); System.out.println("當(dāng)前請求路徑:"+path); System.out.println("=========進入攔截器1==================="); if (path.matches(Const.NO_INTERCEPTOR_PATH)) { //不需要的攔截直接過 System.out.println("=========無需攔截==================="); return true; } else { System.out.println("=========開始攔截==================="); // 這寫你攔截需要干的事兒,比如取緩存,SESSION,權(quán)限判斷等 String token = request.getParameter("token"); if(token == null){ System.out.println("=========攔截完成==================="+false); return false; } System.out.println("=========攔截完成==================="+true); return true; } } }
關(guān)鍵代碼:path.matches(Const.NO_INTERCEPTOR_PATH 就是基于正則匹配的url。
package com.zp.springbootdemo.interceptor; /** * @author zp * @explain 常量類 */ public class Const { public static final String SUCCESS = "SUCCESS"; public static final String ERROR = "ERROR"; public static final String FIALL = "FIALL"; /**********************對象和個體****************************/ public static final String SESSION_USER = "loginedAgent"; // 用戶對象 public static final String SESSION_LOGINID = "sessionLoginID"; // 登錄ID public static final String SESSION_USERID = "sessionUserID"; // 當(dāng)前用戶對象ID編號 public static final String SESSION_USERNAME = "sessionUserName"; // 當(dāng)前用戶對象ID編號 public static final Integer PAGE = 10; // 默認分頁數(shù) public static final String SESSION_URL = "sessionUrl"; // 被記錄的url public static final String SESSION_SECURITY_CODE = "sessionVerifyCode"; // 登錄頁驗證碼 // 時間 緩存時間 public static final int TIMEOUT = 1800;// 秒 public static final String ON_LOGIN = "/logout.htm"; public static final String LOGIN_OUT = "/toLogout"; // 不驗證URL anon:不驗證/authc:受控制的 public static final String NO_INTERCEPTOR_PATH =".*/((.css)|(.js)|(images)|(login)|(anon)).*"; }
測試:
請求地址:http://127.0.0.1:8080/user/getUser?token=123
結(jié)果:
基于注解的攔截器
①創(chuàng)建注解:
package com.zp.springbootdemo.interceptor; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 在需要登錄驗證的Controller的方法上使用此注解 */ @Target({ElementType.METHOD})// 可用在方法名上 @Retention(RetentionPolicy.RUNTIME)// 運行時有效 public @interface LoginRequired { }
②創(chuàng)建攔截器:
package com.zp.springbootdemo.interceptor; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.lang.reflect.Method; public class AuthorityInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("===============進入攔截器2====================="); // 如果不是映射到方法直接通過 if (!(handler instanceof HandlerMethod)) { System.out.println("===============無需攔截====================="); return true; } // ①:START 方法注解級攔截器 HandlerMethod handlerMethod = (HandlerMethod) handler; Method method = handlerMethod.getMethod(); // 判斷接口是否需要登錄 LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class); // 有 @LoginRequired 注解,需要認證 if (methodAnnotation != null) { // 這寫你攔截需要干的事兒,比如取緩存,SESSION,權(quán)限判斷等 System.out.println("===============開始攔截====================="); String token = request.getParameter("token"); if(token == null){ System.out.println("=========攔截完成==================="+false); return false; } System.out.println("=========攔截完成==================="+true); return true; } System.out.println("===============無需攔截==================="); return true; } }
測試接口代碼1:
package com.zp.springbootdemo.system.controller; import com.zp.springbootdemo.interceptor.LoginRequired; import com.zp.springbootdemo.system.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.Map; @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @GetMapping("/getUser") //@LoginRequired public Map<String,String> getUser(@RequestParam Map<String,String> user){ return userService.getUser(user); } }
http://127.0.0.1:8080/user/getUser?token=123
結(jié)果:
測試接口代碼2:
package com.zp.springbootdemo.system.controller; import com.zp.springbootdemo.interceptor.LoginRequired; import com.zp.springbootdemo.system.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.Map; @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @GetMapping("/getUser") @LoginRequired public Map<String,String> getUser(@RequestParam Map<String,String> user){ return userService.getUser(user); } }
請求地址:
http://127.0.0.1:8080/user/getUser token=123
結(jié)果:
看完這篇關(guān)于SpringBoot怎么配置攔截器的文章,如果覺得文章內(nèi)容寫得不錯的話,可以把它分享出去給更多人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。