springboot自動以filter,interceptor,listener實現自定義過濾、攔截、監聽
阿新 • • 發佈:2018-12-06
1:自定義攔截器
(1)實現Filter介面
(2)添加註解WebFilter,指定要過濾的路徑、指定filer的名字、指定初始化引數
(3)新增@ServletComponentScan註解開啟掃描servlet元件
package top.lrshuai.fli.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; /** * * 使用註解標註過濾器 * @WebFilter將一個實現了javax.servlet.Filter介面的類定義為過濾器 * 屬性filterName 宣告過濾器的名稱,可選 * 屬性urlPatterns指定要過濾 的URL模式,這是一個數組引數,可以指定多個。也可使用屬性value來宣告.(指定要過濾的URL模式是必選屬性) */ @WebFilter(filterName="myFilter",urlPatterns={"/*"}) public class MyFilter implements Filter{ @Override public void destroy() { System.out.println("myfilter 的 銷燬方法"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("myfilter 的 過濾方法。這裡可以執行過濾操作"); //繼續下一個攔截器 chain.doFilter(request, response); } @Override public void init(FilterConfig arg0) throws ServletException { System.out.println("myfilter 的 初始化方法"); } }
過濾器最先執行所有請求路徑是/*的請求。
2:自定義實現攔截器
(1)實現InterceptorHandler介面
(2) 攔截器preHandler(controller之前執行)和postHandler(controller執行之後,檢視被渲染之前執行)方法和
afterCompletion(請求結束之後呼叫,也就是檢視渲染完成之後呼叫。主要用於資源清理工作)
package top.lrshuai.fli.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; /** * 可以驗證使用者是否登入來攔截,沒登陸返回false * @author tyro * */ public class LoginInterceptor implements HandlerInterceptor{ @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { System.out.println("LoginInterceptor 在整個請求結束之後被呼叫,也就是在DispatcherServlet 渲染了對應的檢視之後執行(主要是用於進行資源清理工作)"); } @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { System.out.println("LoginInterceptor 請求處理之後進行呼叫,但是在檢視被渲染之前(Controller方法呼叫之後)"); } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception { System.out.println("LoginInterceptor 在請求處理之前進行呼叫(Controller方法呼叫之前) 這裡是攔截的操作"); String user = (String) request.getSession().getAttribute("user"); System.out.println("user="+user); if(null == user || "".equals(user)){ response.setContentType("text/html;charset=utf-8"); response.getWriter().println("你沒登陸,請去登入頁面:<a href='http://localhost:8080/login'>登入</a>。"); return false; } return true; } }
package top.lrshuai.fli.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class MyInterceptor implements HandlerInterceptor{ @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { System.out.println("MyInterceptor 在整個請求結束之後被呼叫,也就是在DispatcherServlet 渲染了對應的檢視之後執行(主要是用於進行資源清理工作)"); } @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { System.out.println("MyInterceptor 請求處理之後進行呼叫,但是在檢視被渲染之前(Controller方法呼叫之後)"); } @Override public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception { System.out.println("MyInterceptor 在請求處理之前進行呼叫(Controller方法呼叫之前)這裡是攔截的操作"); return true; } }
定義完攔截器之後。要對攔截器進行註冊,才能使攔截器起到作用。實現
WebMvcConfigurerAdapter.重寫addInterceptors方法即可程式碼如下:指定攔截器攔截的請求和排除攔截的請求
package top.lrshuai.fli.interceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebConfigurer extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// addPathPatterns 用於新增攔截規則
// excludePathPatterns 排除攔截
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**").excludePathPatterns("/login");
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
super.addInterceptors(registry);
}
}
(3)自定義監聽器:ServletContextListerner HttpSessionListener。實現這兩個介面。並且新增@weblinstener註解指定其
為自定義web監聽器
package top.lrshuai.fli.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class ServletListener implements ServletContextListener{
@Override
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("servlet 銷燬時呼叫");
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("servlet 初始化時呼叫");
}
}
@RequestMapping("/logout")
public String logout(){
System.out.println("這是在logout方法裡銷燬session試試");
((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest().getSession().removeAttribute("user");
((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest().getSession().invalidate();
return "logout success";
}
package top.lrshuai.fli.listener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
@WebListener
public class SessionListener implements HttpSessionListener{
@Override
public void sessionCreated(HttpSessionEvent arg0) {
System.out.println("監聽 建立session");
}
@Override
public void sessionDestroyed(HttpSessionEvent arg0) {
System.out.println("監聽 銷燬session");
}
}
session銷燬後執行的對應監聽器的方法