Spring boot servlet,filter,Listener,Interceptor
Posted xiaodujava
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring boot servlet,filter,Listener,Interceptor相关的知识,希望对你有一定的参考价值。
文章目录
Spring boot servlet,filter,Listener,Interceptor
上一节
源码
Spring boot 使用servlet
第一种方式:使用注解@WebServlet
@WebServlet 是java Servlet 3.0 提供的注解,标注在类上声明这是一个servlet, 类需要继承servlet
使用示例
@WebServlet(value = "/test/servlet", name = "myServlet1", asyncSupported = true,
loadOnStartup = 0,
initParams = {
@WebInitParam(name = "param1", value = "value1")}
)
public class MyServlet1 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("reqeust myServlet1");
// 获取 init-param
String param1 = getServletConfig().getInitParameter("param1");
System.out.println("myServlet1 listener = " + getServletContext().getAttribute("myListener"));
super.service(req, resp);
}
}
属性简介
@WebServlet 中的每个属性都基本对应我们在web.xml中的配置
属性 | web.xml | 备注 |
---|---|---|
name | <servlet-name> | servlet 名称 |
value | <url-pattern> | 匹配的url |
urlPatterns | <url-pattern> | 匹配的url正则,和value必须二选一有值 |
loadOnStartup | <load-on-startup> | 启动加载顺序 |
initParams | <init-param> | 初始化参数 |
description | <description> | 描述 |
displayName | <display-name> | 显示的名称 |
<servlet>
<servlet-name></servlet-name>
<servlet-class></servlet-class>
<init-param>
<param-name></param-name>
<param-value></param-value>
</init-param>
<description></description>
<load-on-startup></load-on-startup>
<async-supported></async-supported>
</servlet>
<servlet-mapping>
<servlet-name></servlet-name>
<url-pattern></url-pattern>
</servlet-mapping>
若在springboot 项目中使用的 嵌入Web容器;则需要使用@ServletComponentScan 扫描;
@WebFilter 过滤器和@WebLIstener 监听器使用同理也需要扫描
@SpringBootApplication
@ServletComponentScan(value = {"com.xiaodu.servlet", "com.xiaodu.filter", "com.xiaodu.listener"})
public class StartApplication {
public static void main(String[] args) {
SpringApplication.run(StartApplication.class, args);
}
}
第二种方式:使用spring 提供的方式ServletRegistrationBean
在配置类中加入ServletRegistrationBean ; 即可使用
@Bean
public ServletRegistrationBean<MyServlet2> servletRegistrationBean() {
ServletRegistrationBean<MyServlet2> servletRegistrationBean = new ServletRegistrationBean<>();
servletRegistrationBean.setServlet(new MyServlet2()); // 设置servlet
servletRegistrationBean.addUrlMappings("/test/servlet2"); // url
servletRegistrationBean.setLoadOnStartup(0); // 启动加载顺序
servletRegistrationBean.setAsyncSupported(true); // 是否支持异步
servletRegistrationBean.setName("myServlet2"); // servlet-name
// init-param
Map<String, String> initParam = new HashMap<>();
initParam.put("param", "value");
servletRegistrationBean.setInitParameters(initParam);
return servletRegistrationBean;
}
spring boot 使用 filter
第一种方式:注解 @WebFilter
@webFilter 标注在类上,类需要继承Filter 实现doFilter 方法
@WebFilter(value = "/test/*", filterName = "myServletFilter1",
initParams ={
@WebInitParam(name = "filer1", value = "filer1-Value")
}
)
public class MyServletFilter1 implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("myFilter 1");
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
String filer1 = filterConfig.getInitParameter("filer1");
System.out.println("myFilter1 initParam = " + filer1);
}
}
属性简介
属性 | web.xml | 备注 |
---|---|---|
description | <description> | 描述 |
displayName | <display-name> | 显示名称 |
initParams | <init-param> | 初始参数 |
filterName | <filter-name> | filter-name |
servletNames | <servlet-name> | 过滤那些servlet,通过servletName指定 |
value | </url-pattern> | url |
urlPatterns | </url-pattern> | url |
asyncSupported | <async-supported> | 是否支持异步 |
<filter>
<filter-name></filter-name>
<filter-class></filter-class>
<async-supported></async-supported>
<description></description>
<init-param>
<param-name></param-name>
<param-value></param-value>
</init-param>
<display-name></display-name>
</filter>
<filter-mapping>
<filter-name></filter-name>
<url-pattern></url-pattern>
<servlet-name></servlet-name>
</filter-mapping>
第二种方式: 使用 FilterRegistrationBean
@Bean
public FilterRegistrationBean<MyServletFilter2> filterRegistrationBean() {
FilterRegistrationBean<MyServletFilter2> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new MyServletFilter2());
// 指定过滤路径
registrationBean.addUrlPatterns("/test/*");
// 指定过滤servletRegistrantionBean
// registrationBean.addServletRegistrationBeans(servletRegistrationBean());// 可以过滤那个servlet
// 指定过滤servlet
// registrationBean.addServletNames("myServlet2");
// init filter param
registrationBean.addInitParameter("filter2", "filter2-value");
return registrationBean;
}
spring boot 使用 Listener
第一种方式:注解@WebListener
@WebListener(value = "testListener")
public class MyServletContentListener implements ServletContextListener {
private ServletContext servletContext;
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("listener init");
this.servletContext = sce.getServletContext();
servletContext.setAttribute("myListener", "attribute");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("listener destroy");
}
}
第二种方式:spring 提供的ServletListenerRegistrationBean
@Bean
public ServletListenerRegistrationBean<MyServletContentListener2> servletListenerRegistrationBean() {
ServletListenerRegistrationBean<MyServletContentListener2> servletListenerRegistrationBean = new ServletListenerRegistrationBean<>();
servletListenerRegistrationBean.setListener(new MyServletContentListener2());
return servletListenerRegistrationBean;
}
springboot 使用interceptor
interceptor 是spring 提供的拦截器,作用类似servlet Filter 的作用;不过他们使命不相同; filter 对 request 和 response 进行过滤任务,例如字符集设置; interceptor 则是更进一步能够拦截到具体方法执行前,可以对方法中的参数进行校验和权限认证等
创建拦截器
@Component
public class MyInterceptor1 implements HandlerInterceptor {
// 方法执行前拦截
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("interceptor preHandle");
return true;
}
// 方法处理后拦截
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("interceptor postHandle");
}
// 处理完成后,报错不报错都走
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("interceptor afterCompletion");
}
}
加入和配置拦截器
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
@Qualifier("myInterceptor1")
private HandlerInterceptor handlerInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 添加拦截器
registry.addInterceptor(handlerInterceptor)
// 拦截url 配置
.addPathPatterns("/test/**");
}
}
filer 和 interceptor 的区别和执行顺序
区别:
filter:
1. filter 是Java提供的servlet 技术规范中的;是在servlet 前后执行;是一种函数回调
interceptor:
interceptor 是 spring 框架提供的基于aop 和Java反射机制在方法执行前后进行拦截;
执行顺序:
filter前 -> interceptor.preHandle -> servlet(controller) -> interceptor.postHandle -> filter后
下一节
以上是关于Spring boot servlet,filter,Listener,Interceptor的主要内容,如果未能解决你的问题,请参考以下文章