SpringBoot中使用Servlet与更改DispatcherServlet默认Url
Springboot开发web应用过程中要用到过滤Filter和监听器Listener,
Springboot的主Servlet为 DispatcherServlet,其默认的url-pattern为“/”。也许我们在应用中还需要定义更多的Servlet,该如何使用SpringBoot来完成呢?
在spring boot中添加自己的Servlet有两种方法,代码注册Servlet和注解自动注册(Filter和Listener也是如此)。
一、代码注册通过ServletRegistrationBean、 FilterRegistrationBean 和 ServletListenerRegistrationBean 获得控制。
也可以通过实现 ServletContextInitializer 接口直接注册。
1.实现MyServlet.java
public class MyServlet extends HttpServlet{
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println(">>>>>>>>>>doGet()<<<<<<<<<<<"); doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println(">>>>>>>>>>doPost()<<<<<<<<<<<"); }
}
2.SpringBoot启动时代码注入Servlet
@SpringBootApplication public class SpringBootSampleApplication { public static void main(String[] args) { SpringApplication.run(SpringBootSampleApplication.class, args); } /** * 修改DispatcherServlet默认配置 * */ @Bean public ServletRegistrationBean dispatcherRegistration(DispatcherServlet dispatcherServlet) { ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet); registration.getUrlMappings().clear(); registration.addUrlMappings("*.do"); registration.addUrlMappings("*.json"); return registration; } /** * 使用代码注册Servlet(不需要@ServletComponentScan注解) */ @Bean public ServletRegistrationBean servletRegistrationBean() { return new ServletRegistrationBean(new MyServlet(), "/xs/*");// ServletName默认值为首字母小写,即myServlet } }
二、在 SpringBootApplication 上使用@ServletComponentScan 注解后,Servlet、Filter、Listener 可以直接通过 @WebServlet、@WebFilter、@WebListener 注解自动注册,无需其他代码。
1. 过滤器LoginFilter.java
@WebFilter(value="/*") public class LoginFilter implements Filter { public LoginFilter() { System.out.println("过滤器初始化"); } public void destroy() { System.out.println("过滤器销毁"); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub // place your code here System.out.println("执行过滤操作>>>>>"); // pass the request along the filter chain chain.doFilter(request, response); } public void init(FilterConfig fConfig) throws ServletException { } }
2.SpringBoot启动类添加组件扫描注解@ServletComponentScan
@SpringBootApplication @ServletComponentScan public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
转载请注明来源:SpringBoot中使用Servlet与更改DispatcherServlet默认Url