代码:https://gitee.com/laputa219/springboot_demo/tree/master/boot_servlet
一、使用步骤
1.1 引入依赖
<dependency>
<groupId>org.springframework.boot
</groupId>
<artifactId>spring-boot-starter-web
</artifactId>
</dependency>
注:有些高版本springboot引入会报错,这里我引入的是2.2.5版本;
1.2 编写Servlet
@WebServlet("/my")
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req
, HttpServletResponse resp
){
doPost(req
,resp
);
}
@Override
protected void doPost(HttpServletRequest req
, HttpServletResponse resp
){
System
.out
.println("请求参数name:"+req
.getParameter("name"));
}
}
1.3 编写Filter
@WebFilter(urlPatterns
= "/*", filterName
= "myFilter ",
initParams
= {@WebInitParam(name
= "excludes", value
= "/login/*")}
)
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig
){
String excludes
= filterConfig
.getInitParameter("excludes");
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 destroy() {
System
.out
.println(">>>>>>MyFilter销毁");
}
}
1.4 编写Listener
@WebListener
public class MyListener implements ServletRequestListener {
@Override
public void requestDestroyed(ServletRequestEvent sre
) {
System
.out
.println(">>>>>>MyListener销毁");
}
@Override
public void requestInitialized(ServletRequestEvent sre
) {
System
.out
.println(">>>>>>MyListener初始化");
}
}
1.5 启动类加@ServletComponentScan注解
@SpringBootApplication
@ServletComponentScan
public class BootServletApplication {
public static void main(String
[] args
) {
SpringApplication
.run(BootServletApplication
.class, args
);
}
}
注:@WebServlet @WebFilter("/*") @WebListener 三个注解分别对应Servlet、过滤器、监听器,监听器也支持其他监听,实现对应的监听器接口即可。
二、测试
访问:http://localhost:8080/my?name=张三 输出结果:
>>>>>>MyListener初始化
>>>>>>MyFilter拦截
请求参数name:张三
>>>>>>MyListener销毁
三、补充
整合Filter的其他方式
filter定义使用@Component注解
@Component
public class AuthFilter implements Filter {
}
注册
@Configuration
public class ConfigurerAdapter implements WebMvcConfigurer {
@Bean
public FilterRegistrationBean
securityFilterRegistration() {
FilterRegistrationBean registrationBean
= new FilterRegistrationBean();
registrationBean
.setFilter(new AuthFilter());
registrationBean
.addUrlPatterns("/*");
registrationBean
.setName("authFilter");
registrationBean
.setOrder(2);
return registrationBean
;
}
}