简体   繁体   English

如何使用Spring Boot注册辅助servlet?

[英]How can I register a secondary servlet with Spring Boot?

I have an extra servlet I need to register in my application. 我需要在我的应用程序中注册一个额外的servlet。 However with Spring Boot and its Java Config, I can't just add servlet mappings in a web.xml file. 但是使用Spring Boot及其Java Config,我不能只在web.xml文件中添加servlet映射。

How can I add additional servlets? 如何添加其他servlet?

Also available is the ServletRegistrationBean 另外还有ServletRegistrationBean

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

Which ended up being the path I took. 最终成为我走的路。

Just add a bean for the servlet . 只需为servlet添加一个bean It'll get mapped to /{beanName}/ . 它将被映射到/{beanName}/

@Bean
public Servlet foo() {
    return new FooServlet();
}

You can register multiple different servlet with different ServletRegistrationBean like @Bean in Application class and you can register a servlet has multiple servlet mapping; 您可以在Application类中使用不同的ServletRegistrationBean注册多个不同的servlet,如@Bean,并且可以注册一个具有多个servlet映射的servlet;

   @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");
   }

We can also register the Servlet as follow way: 我们也可以按照以下方式注册Servlet:

@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);
  }
}

If you're using embedded server, you can annotate with @WebServlet your servlet class: 如果您使用的是嵌入式服务器,则可以使用@WebServlet注释您的servlet类:

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

From @WebServlet : 来自@WebServlet

Annotation used to declare a servlet. 用于声明servlet的注释。

This annotation is processed by the container at deployment time, and the corresponding servlet made available at the specified URL patterns. 该注释在部署时由容器处理,并且相应的servlet在指定的URL模式下可用。

And enable @ServletComponentScan on a base class: 并在基类上启用@ServletComponentScan

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

Please note that @ServletComponentScan will work only with embedded server: 请注意, @ ServletComponentScan仅适用于嵌入式服务器:

Enables scanning for Servlet components (filters, servlets, and listeners). 允许扫描Servlet组件(过滤器,servlet和侦听器)。 Scanning is only performed when using an embedded web server. 仅在使用嵌入式Web服务器时执行扫描。

More info: The @ServletComponentScan Annotation in Spring Boot 更多信息: Spring Boot中的@ServletComponentScan注释

Also available in the BeanDefinitionRegistryPostProcessor 也可以在BeanDefinitionRegistryPostProcessor中使用

package bj;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@SpringBootApplication
class App implements BeanDefinitionRegistryPostProcessor {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        registry.registerBeanDefinition("myServlet", new RootBeanDefinition(ServletRegistrationBean.class,
                () -> new ServletRegistrationBean<>(new HttpServlet() {
                    @Override
                    protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
                        resp.getWriter().write("hello world");
                    }
                }, "/foo/*")));
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    }
}

This way worked for me, having a servlet called WS01455501EndpointFor89 这种方式对我有用,有一个名为WS01455501EndpointFor89的servlet

@Bean
public ServletRegistrationBean<WS01455501EndpointFor89> servletRegistrationBeanAlt(ApplicationContext context) {
    ServletRegistrationBean<WS01455501EndpointFor89> servletRegistrationBean = new ServletRegistrationBean<>(new WS01455501EndpointFor89(),
            "/WS01455501Endpoint");
    servletRegistrationBean.setLoadOnStartup(1);
    return servletRegistrationBean;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Spring Boot中注册Alexa V2 Servlet - How can I register Alexa V2 Servlet in Spring Boot 如何在Spring Boot XML文件中注册servlet? - How to register a servlet in Spring Boot XML file? 如何在 Spring Boot 的不同端口上注册 servlet? - How to register servlet on a different port in spring boot? 如何在 Spring-Boot 中注册启用了“异步支持”的 servlet? - How to register a servlet with enabled "async-supported" in Spring-Boot? 如何在Spring Boot中注册并使用jackson AfterburnerModule? - How can I register and use the jackson AfterburnerModule in Spring Boot? 我可以将可运行的Spring Boot Restlet应用程序表示为Servlet吗? - Can I represent a runnable Spring boot restlet application as a servlet? 如何在我的 Spring 引导应用程序的 JPA 配置中注册我的自定义 sql 驱动程序? - How can I register my custom sql driver in JPA configurations of my Spring Boot application? 如何在 Spring Boot 中注册 ServletContextListener - How to register ServletContextListener in spring boot 我如何运行Spring Boot Servlet页面 - How do I run Spring Boot Servlet pages 如何注册可以被多个WAR共享的bean(Spring boot + Tomcat) - How to register beans that can be shared by multiple WARs (Spring boot + Tomcat)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM