为Spring boot项目增加Servlet

为Spring boot项目增加Servlet有好多种方式

方式1

Just add a bean for the servlet. It’ll get mapped to /{beanName}/.

1
2
3
4
@Bean
public Servlet foo() {
return new FooServlet();
}

Note that if you actually want it mapped to /something/* rather than /something/ you will need to use ServletRegistrationBean

方式2

使用ServletRegistrationBean

1
2
3
4
@Bean
public ServletRegistrationBean servletRegistrationBean(){
return new ServletRegistrationBean(new FooServlet(),"/someOtherUrl/*");
}

如果想增加多个的话,就类似下面的方式

1
2
3
4
5
6
7
8
9
10
11
@Bean
public ServletRegistrationBean axisServletRegistrationBean() {
ServletRegistrationBean registration = new ServletRegistrationBean(new AxisServlet(), "/services/*");
registration.addUrlMappings("*.jws");
return registration;
}

@Bean
public ServletRegistrationBean adminServletRegistrationBean() {
return new ServletRegistrationBean(new AdminServlet(), "/servlet/AdminServlet");
}

方式3

通过实现WebApplicationInitializer或者ServletContextInitializer或者ServletContainerInitializer接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Configuration
public class ConfigureWeb implements ServletContextInitializer, EmbeddedServletContainerCustomizer {

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
registerServlet(servletContext);
}

private void registerServlet(ServletContext servletContext) {
log.debug("register Servlet");
ServletRegistration.Dynamic serviceServlet = servletContext.addServlet("ServiceConnect", new ServiceServlet());

serviceServlet.addMapping("/api/ServiceConnect/*");
serviceServlet.setAsyncSupported(true);
serviceServlet.setLoadOnStartup(2);
}
}

方式4

如果使用内嵌的server的话,那么还可以使用@WebServlet WebServlet

Annotation used to declare a servlet.

This annotation is processed by the container at deployment time, and the corresponding servlet made available at the specified URL patterns.

1
2
@WebServlet(urlPatterns = "/example")
public class ExampleServlet extends HttpServlet

然后增加注解@ServletComponentScan:

1
2
3
4
@ServletComponentScan
@EntityScan(basePackageClasses = { ExampleApp.class, Jsr310JpaConverters.class })
@SpringBootApplication
public class ExampleApp

Please note that @ServletComponentScan will work only with embedded server:

Enables scanning for Servlet components (filters, servlets, and listeners). Scanning is only performed when using an embedded web server.

参考资料

# spring

Comentarios

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×