Foreword
In Spring Boot web.xml file has been removed, if the need to register to add Servlet, Filter, Listener for the Spring Bean, there are two ways in Spring Boot in:
- Use Servlet annotation @ WebServlet 3.0 API's, @ WebFilter, @ Listener to configure.
- Spring Boot JavaConfig way to configure Bean notes to be configured.
Before registration
When using Servlet, we need to add annotations in Spring Boot @ServletComponentScan entrance class, tell Spring Boot to scan using the following registration Servlet, Filter, Listener.
@SpringBootApplication
@ServletComponentScan
public class SpringBootServletApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootServletApplication.class, args);
}
}
Registration Servlet
1. @ WebServlet property
Attributes | Types of | description |
---|---|---|
name | String | Servlet name is specified, equivalent to
|
value | String[] | UrlPatterns equivalent properties should not be used simultaneously both |
urlPatterns | String[] | Servlet URL to specify a set of matching patterns. Equivalent to
|
loadOnStartup | int | Servlet specified loading sequence, equivalent to
|
initParams | WebInitParam[] | Servlet specifies a set of initialization parameters, equivalent to
|
asyncSupported | boolean | Statement Servlet support asynchronous modes of operation, equivalent to
|
smallIcon | String | This Servlet small icon |
largeIcon | String | This Servlet large icons |
description | String | The Servlet description information, equivalent to
|
displayName | String | Displaying the name of the Servlet, usually with the use of tools, it is equivalent to
|
2. Example
@WebServlet(urlPatterns = "/TestServlet")
public class TestServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -3325041776508043481L;
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
doPost(req, resp);
}
/*
* 实现请求uri和header打印,另外返回一个json
*/
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
System.out.println("RequestURI:" + req.getRequestURI());
System.out.println("Request Headers:");
StringBuilder sb = new StringBuilder();
Enumeration<?> names = req.getHeaderNames();
while (names.hasMoreElements()) {
String name = names.nextElement().toString();
Enumeration<?> hs = req.getHeaders(name);
sb.append(name).append(":");
while (hs.hasMoreElements()) {
sb.append(hs.nextElement()).append(";");
}
}
System.out.println(sb);
ObjectMapper om=new ObjectMapper();
UserEntity user=new UserEntity();
user.setId(1L);
user.setUserName("zwqh");
user.setUserSex("男");
user.setHeaders(sb.toString());
String resultJson=om.writeValueAsString(user);
resp.setContentType("application/json;charset=UTF-8");
resp.getWriter().print(resultJson);
}
}
Wherein @WebServlet (urlPatterns = "/ TestServlet") is equivalent to the following code:
<servlet>
<!-- 类名 -->
<servlet-name> TestServlet </servlet-name>
<!-- 所在的包 -->
<servlet-class> cn.zwqh.springbboot.servlet.TestServlet </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> TestServlet </servlet-name>
<!-- 访问的url路径地址 -->
<url-pattern> /TestServlet </url-pattern>
</servlet-mapping>
3. Test
Browser access http://127.0.0.1:8080/TestServlet
log output:
Registration Filter
1. @ WebFilter property
Attributes | Types of | description |
---|---|---|
filterName | String | Filter name is specified, equivalent to
|
value | String[] | UrlPatterns equivalent properties should not be used simultaneously both |
urlPatterns | String[] | Filter URL to specify a set of matching patterns. Equivalent to
|
servletNames | String[] | Filter is applied which specifies Servlet. The value of the name attribute @WebServlet, or in web.xml
|
initParams | WebInitParam[] | Filter specifies a set of initialization parameters, equivalent to
|
dispatcherTypes | DispatcherType[] | Filter specified forwarding modes, including: ASYNC, ERROR, FORWARD, INCLUDE, REQUEST |
asyncSupported | boolean | Statement Filter supports asynchronous mode of operation, equivalent to
|
smallIcon | String | Filter this small icon |
largeIcon | String | Filter this large icons |
description | String | Filter the description information, equivalent to
|
displayName | String | Filter the display name, usually with the tools, it is equivalent to
|
2. Example
@WebFilter(urlPatterns = { "/TestServlet" }) // 注册拦截器,并添加拦截路径‘/TestServlet’
public class TestFilter implements Filter {
/**
* 初始化,只在项目启动的时候执行一次
*/
@Override
public void init(FilterConfig filterConfig) {
System.out.println("===> TestFilter init");
}
/**
* 用于存放过滤器的业务逻辑实现代码
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
chain.doFilter(request, response);// 处理请求和响应的分界线
System.out.println("===> chain.doFilter 后执行处理 response 的相关方法");
// 在response header里设置一个token
setToken(response);
}
private void setToken(ServletResponse response) {
HttpServletResponse res = (HttpServletResponse) response;
String token = UUID.randomUUID().toString();
res.setHeader("Token", token);
System.out.println("===> 设置了token:" + token);
}
/**
* 销毁,在项目关闭,Servlet 容器销毁前调用
*/
@Override
public void destroy() {
System.out.println("===> TestFilter destroy");
}
}
3. Test
Browser access http://127.0.0.1:8080/TestServlet:
Log Print:
4.Filter major usage scenarios
- Disable the browser's cache (caching process)
- Solve the problem of Chinese garbled
- Login authentication and rights management
- User authorization, is responsible for checking the user's request, the request upon request filtering illegal user
- 日志记录,详细记录某些特殊的用户请求
- 其他场景
注册 Listener
1.@Listener 属性
属性 | 类型 | 描述 |
---|---|---|
value | String | 侦听器Listener的描述 |
2.示例
与 ServletContext 相关的监听
Servlet 的监听器 Listener 是实现了 javax.servlet.ServletContextListener 接口的服务器端程序,随着 Web 应用启动而启动,只初始化一次,也随着 Web 应用停止而销毁。其主要作用是做一些初始化的内容添加工作,如参数和对象等。
@WebListener
public class ContextListener implements ServletContextListener, ServletContextAttributeListener{
public static final String INITIAL_CONTENT = "Content created in servlet Context";
/**
* ServletContext创建
*/
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("===> context initialized");
ServletContext servletContext = sce.getServletContext();
servletContext.setAttribute("content", INITIAL_CONTENT);
}
/**
* ServletContext销毁
*/
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("===> context destroyed");
}
/**
* context属性新增
*/
@Override
public void attributeAdded(ServletContextAttributeEvent scae) {
System.out.println("===> context attribute added");
}
/**
* context属性移除
*/
@Override
public void attributeRemoved(ServletContextAttributeEvent scae) {
System.out.println("===> context attribute removed");
}
/**
* context属性替换
*/
@Override
public void attributeReplaced(ServletContextAttributeEvent scae) {
System.out.println("===> context attribute replaced");
}
}
与 HttpSession 相关的监听
@WebListener
public class SessionListener implements HttpSessionListener, HttpSessionIdListener, HttpSessionAttributeListener,
HttpSessionActivationListener {
/**
* session被创建时
*/
@Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("===> session created");
}
/**
* session被销毁时
*/
@Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("===> session destroyed");
}
/**
* sessionId改变
*/
@Override
public void sessionIdChanged(HttpSessionEvent se, String oldSessionId) {
System.out.println("===> session id changed");
}
/**
* session属性新增
*/
@Override
public void attributeAdded(HttpSessionBindingEvent se) {
System.out.println("===> session attribute added");
}
/**
* session属性移除
*/
@Override
public void attributeRemoved(HttpSessionBindingEvent se) {
System.out.println("===> session attribute removed");
}
/**
* session属性替换
*/
@Override
public void attributeReplaced(HttpSessionBindingEvent se) {
System.out.println("===> session attribute replaced");
}
/**
* session的钝化,内存的数据写入到硬盘上的过程。
*/
@Override
public void sessionWillPassivate(HttpSessionEvent se) {
System.out.println("===> session will passivate");
}
/**
* session的活化,将硬盘的数据恢复到内存中。
*/
@Override
public void sessionDidActivate(HttpSessionEvent se) {
System.out.println("===> session did activate");
}
}
与 ServletRequest 相关的监听
@WebListener
public class RequestListener implements ServletRequestListener,ServletRequestAttributeListener {
/**
* 请求即将进入Web应用程序的范围/请求初始化时
*/
@Override
public void requestInitialized(ServletRequestEvent sre) {
System.out.println("===> request initialized");
}
/**
* 请求即将进入Web应用程序的范围/请求销毁时
*/
@Override
public void requestDestroyed(ServletRequestEvent sre) {
System.out.println("===> request destroyed");
}
/**
* request属性新增
*/
@Override
public void attributeAdded(ServletRequestAttributeEvent srae) {
System.out.println("===> request attribute added");
}
/**
* request属性移除
*/
@Override
public void attributeRemoved(ServletRequestAttributeEvent srae) {
System.out.println("===> request attribute removed");
}
/**
* request属性替换
*/
@Override
public void attributeReplaced(ServletRequestAttributeEvent srae) {
System.out.println("===> request attribute replaced");
}
}
3.项目相关日志输入(启动和停止)
先执行 contextInitialzed 方法在执行 TestFilter 类的 init 方法,
contextDestroyed 方法在 TestFilter 类 destroy 方法执行后执行。
示例代码
非特殊说明,本文版权归 朝雾轻寒 所有,转载请注明出处.
原文标题:Spring Boot 2.X(十):自定义注册 Servlet、Filter、Listener
原文地址:https://www.zwqh.top/article/info/17
如果文章对您有帮助,请扫码关注下我的公众号,文章持续更新中...