Spring MVC中的攔截器(Interceptor)相似於Servlet中的過濾器(Filter),它主要用於攔截用戶請求並做相應的處理。例如經過攔截器能夠進行權限驗證、記錄請求信息的日誌、判斷用戶是否登陸等。在SpringMVC中經過實現HandlerInterceptor接口實現自定義攔截器類。html
package com.springmvc.intercept; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MyIntercept implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("=========攔截器當中的handle方法========="); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("=======在HandlerAdapter以後執行,在DispatcherServlet解析視圖以前執行====="); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("=========呈現以後調用========="); } }
<!--利用default-servlet放行資源--> <mvc:default-servlet-handler/> <!--配置攔截器--> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/my/**"/> <bean class="com.springmvc.intercept.MyIntercept"></bean> </mvc:interceptor> </mvc:interceptors>
@Controller @RequestMapping("/my") public class MyController { @RequestMapping("/doFirst") public String doFirst(){ System.out.println("=========控制器中的方法========="); return "index"; }
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.4.1.Final</version> </dependency>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>測試案例</title> </head> <body> <form action="/my/validate" method="post"> 編號:<input type="text" name="uid"/><br/> 姓名:<input type="text" name="uName"/><br/> 郵箱:<input type="text" name="email"/><br/> 電話:<input type="text" name="phone"/><br/> 身份證號:<input type="text" name="userCode"/><br/> <input type="submit" value="提交"/> </form> </body> </html>
package com.springmvc.entity; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.Length; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; public class UserInfo { @NotNull(message="編號不能爲空") private Integer uid; @NotNull @Length(min = 2,max = 8,message = "用戶名不能少於2位或大於8位") private String uName; @Email(message = "郵箱格式不正確") private String email; @Pattern(regexp = "/^1[3456789]\\d{9}$/",message = "手機號式不正確") private String phone; @Pattern(regexp = "/(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)/",message = "身份證號格式不正確") private String userCode; public Integer getUid() { return uid; } public void setUid(Integer uid) { this.uid = uid; } public String getuName() { return uName; } public void setuName(String uName) { this.uName = uName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getUserCode() { return userCode; } public void setUserCode(String userCode) { this.userCode = userCode; } }
package com.springmvc.controller; import com.springmvc.entity.UserInfo; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.RequestMapping; import javax.validation.Valid; import java.util.List; @Controller @RequestMapping("/my") public class MyController { @RequestMapping("/doFirst") public String doFirst(){ System.out.println("=========控制器中的方法========="); return "index"; } @RequestMapping("/validate") public String Validate(@Valid UserInfo info, BindingResult bindingResult){ //若是有異常信息 if (bindingResult.hasErrors()){ //獲取異常信息對象 List<ObjectError> allErrors = bindingResult.getAllErrors(); //將異常信息輸出 for (ObjectError errors:allErrors) { System.out.println(errors.getDefaultMessage()); } } return "index"; } }