目錄html
註冊的功能的實現是比較簡單的,可是涉及到一些問題java
咱們須要一個實現HandlerInterceptor接口的類來編寫攔截器實體web
package com.example.demo.interceptor; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component public class TestInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //請求開始前 System.out.println("這裏是攔截器"); return false; //false就攔截了 } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { //攔截器處理完後 } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { //渲染完後,用來釋放資源 } }
咱們須要一個地方加入剛剛的攔截器,繼承WebMvcConfigurerAdapter的類spring
package com.example.demo.configuration; import com.example.demo.interceptor.TestInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Component public class Wendaconfigration extends WebMvcConfigurerAdapter { @Autowired TestInterceptor testInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(testInterceptor); super.addInterceptors(registry); } }
咱們能夠用攔截器帶以及跳轉完成未登入跳轉等功能sql