1. 攔截器
在 Spring Boot 可以可以在以下情況執(zhí)行操作:
在將請(qǐng)求發(fā)送到控制器之前在將響應(yīng)發(fā)送給客戶端之前
2. 攔截器使用
下面實(shí)現(xiàn)一簡(jiǎn)單的登錄驗(yàn)證功能。
2.1 準(zhǔn)備工作
Step1:在前端頁(yè)面添加thymeleaf支持;
<html lang="en" xmlns:th="http://www.thymeleaf.org">
Step2:主要的HTML內(nèi)容如下:
<form method="post" th:action="@{/SignUp}"> <input class="input_Email" type="email" name="email"> <input class="input" type="password" maxlength="20px" name="password"> <button type="submit">登錄</button> </form>
注意:th:action="@{/SignUp}" 中的 URL 的 Controller 中定義。
Step3:Config 中添加視圖控制器,實(shí)現(xiàn) WebMvcConfigurer 接口中的 addViewControllers 方法;
@Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("/SignUp"); registry.addViewController("/SignUp.html").setViewName("/SignUp"); registry.addViewController("/SuccessPage.html").setViewName("/SuccessPage"); }
2.2 Controller
實(shí)現(xiàn)登錄的功能最主要的是Controller。在Controller中,為了簡(jiǎn)單方便,我們不走數(shù)據(jù)庫(kù),直接利用 equal 方法來比較參數(shù)。
@Controller public class SignUpController { @RequestMapping("/SignUp") public String SignUp(@RequestParam("email") String email, @RequestParam("password") String password, Model model, HttpSession session) { if (email.equals("[email protected]") && password.equals("123456")) { session.setAttribute("email",email); return "SuccessPage"; }else { model.addAttribute("msg", "郵箱或密碼錯(cuò)誤"); return "SignUp"; } } }
在前端頁(yè)面插入該 id 為 msg 的輸出信息。
<div style="color: red" th:text="${msg}"></div>
2.3 Interceptor
過濾器的實(shí)現(xiàn)如下:
public class SignUpInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if(request.getSession().getAttribute("email") == null){ request.setAttribute("msg", "你沒有權(quán)限進(jìn)入,請(qǐng)登錄"); request.getRequestDispatcher("SignUp.html").forward(request,response); return false; }else { return true; } } }
2.4 Config
Config 類實(shí)現(xiàn)了 WebMvcConfigurer 接口,添加攔截器需要實(shí)現(xiàn)其中 addInterceptors 方法。
- addPathPatterns:指在和何處添加攔截器,/** 表示該路徑下的所有文件及子目錄的所有文件;
- excludePathPatterns:表示需要排除攔截器的url
@Configuration public class Boot_Config implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new SignUpInterceptor()).addPathPatterns("/**"). excludePathPatterns("/","/SignUp","/SignUp.html"); } }
2.5 測(cè)試
2.5.1 正常登錄
2.5.2 非正常登錄
2.5.3 攔截器
3. 總結(jié)
Spring Boot 是實(shí)現(xiàn)的攔截器與 Spring MVC 是一直的,只不過需要在 Config 中實(shí)現(xiàn)了 addInterceptors 方法。
文章中用到的頁(yè)面放在了下面:
鏈接: https://pan.baidu.com/s/1jmc7Eq0uQCi2QTy2Q7zLdw提取碼: ufjw
input標(biāo)簽實(shí)現(xiàn)了簡(jiǎn)單的驗(yàn)證功能,頁(yè)面預(yù)覽:
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注服務(wù)器之家!
原文鏈接:https://blog.csdn.net/weixin_47243236/article/details/120923200