springboot监听器,过滤器,拦截器
2019-11-29 本文已影响0人
前进的码农
springboot监听器,过滤器,拦截器
servlet3.0注解
package com.ethan.springboottest.servlet;
import javax.servlet.annotation.WebServlet;//注意这里导入的包名,导入其他的包会报错
/**
* @Author: ethan.liu
* @Date: 2019/11/28 10:16
*/
@WebServlet(name = "user",urlPatterns = "/test")
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("--->doGet");
resp.getWriter().print("hi");
resp.getWriter().flush();
resp.getWriter().close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
@Override
public void destroy() {
super.destroy();
System.out.println("--->destroy");
}
}
启动类要加注解
@ServletComponentScan
不然不起作用
@SpringBootApplication
@ServletComponentScan
public class SpringboottestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringboottestApplication.class, args);
}
}
浏览器访问路径为:
http://localhost:8080/test
监听器
servletContextListener、httpSessionListener、servletRequestListener
常见监听器 servletContextListener,httpSessionListener,servletRequestListner
servletContextListener
项目启动的时候调用走contextInitialized项目被kill掉后走contextDestroyed
所以在contextInitialized我们可以做一些初始化的工作,异步加载点数据等等。
@WebListener
public class ServletContextListener implements javax.servlet.ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("ServletContextListener====contextInitialized");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("ServletContextListener====contextDestroyed");
}
}
servletRequestListner
ServletRequestListener的生命周期为请求开始到请求结束比如发一个
http://localhost:8080/user/test请求会先后调用requestInitialized,requestDestroyed
@WebListener
public class ServletRequestListener implements javax.servlet.ServletRequestListener {
@Override
public void requestDestroyed(ServletRequestEvent sre) {
System.out.println("ServletRequestListener====requestDestroyed");
}
@Override
public void requestInitialized(ServletRequestEvent sre) {
System.out.println("ServletRequestListener====requestInitialized");
}
}
httpSessionListener
@WebListener
public class ServletSesstionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("ServletSesstionListener===sessionCreated");
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("ServletSesstionListener===sessionDestroyed");
}
}
@RequestMapping("test")
public Object test(HttpServletRequest httpServletRequest){
//如果这里不设置的话sessionCreated不会创建
httpServletRequest.getSession().setAttribute("123","1234");
System.out.println("sid="+httpServletRequest.getSession().getId());
return "test";
}
//test2和test3输出的id是一样的每次都一样说明session没走创建
@RequestMapping("test2")
public Object test1(HttpServletRequest httpServletRequest){
System.out.println("sid="+httpServletRequest.getSession().getId());
return "test";
}
@RequestMapping("test3")
public Object test3(HttpServletRequest httpServletRequest){
System.out.println("sid="+httpServletRequest.getSession().getId());
return "test";
}
过滤器
类似于你带票了没带票就不让进带了就进入拦截器开始验票,票通过了可以进入controller处理业务。
@WebFilter("/user/*")
@Configuration
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = ((HttpServletRequest) servletRequest);
if (request.getRequestURI().contains("info")){
filterChain.doFilter(servletRequest,servletResponse);
}
servletResponse.getWriter().print("hello");
servletResponse.getWriter().flush();
servletResponse.getWriter().close();
}
@Override
public void destroy() {
}
}
@RequestMapping("test2")被过滤
public Object test1(HttpServletRequest httpServletRequest){
System.out.println("sid="+httpServletRequest.getSession().getId());
return "test";
}
@RequestMapping("info")//通过
public Object test3(HttpServletRequest httpServletRequest){
System.out.println("sid="+httpServletRequest.getSession().getId());
return "test";
}
拦截器
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//最后一个路径为/**
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/user/**");
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.QuoteFieldNames,
SerializerFeature.PrettyFormat,
SerializerFeature.WriteEnumUsingToString,
SerializerFeature.WriteDateUseDateFormat,
SerializerFeature.DisableCircularReferenceDetect);
//long转string
//设置时间
fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
fastConverter.setFastJsonConfig(fastJsonConfig);
converters.add(fastConverter);
}
}
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("url---"+request.getRequestURI());
return true;
}
@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 {
}
}
configureMessageConverters测试表明configureMessageConverters 全局有效果!preHandle拦截的话对指定路径
这里只对时间格式化,做个简单测试,大家可以下源码自己编译测试
目录其效果
从上面的log显示我们可以看到执行的顺序如下:
ServletContextListener====contextInitialized
ServletRequestListener====requestInitialized
MyFilter---doFilter
MyInterceptor---preHandle
user/info controller方法
ServletRequestListener====requestDestroyed