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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20915528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:17:44  来源:igfitidea点击:

How can I register a secondary servlet with Spring Boot?

javaspringspring-boot

提问by checketts

I have an extra servlet I need to register in my application. However with Spring Boot and its Java Config, I can't just add servlet mappings in a web.xmlfile.

我有一个额外的 servlet,需要在我的应用程序中注册。但是,使用 Spring Boot 及其 Java Config,我不能只在web.xml文件中添加 servlet 映射。

How can I add additional servlets?

如何添加额外的 servlet?

采纳答案by chrylis -cautiouslyoptimistic-

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

只需为 servlet 添加一个 bean。它将被映射到/{beanName}/.

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

回答by checketts

Also available is the ServletRegistrationBean

也可用的是 ServletRegistrationBean

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

Which ended up being the path I took.

这最终成为我走的路。

回答by Muzu

You can register multiple different servlet with different ServletRegistrationBean like @Bean in Application class and you can register a servlet has multiple servlet mapping;

您可以使用不同的 ServletRegistrationBean 注册多个不同的 servlet,例如 Application 类中的 @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");
   }

回答by Pramod Yadav

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

回答by Justas

If you're using embedded server, you can annotate with @WebServletyour servlet class:

如果您使用的是嵌入式服务器,则可以使用@WebServletservlet 类进行注释:

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

From @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.

用于声明 servlet 的注解。

该注解在部署时由容器处理,相应的 servlet 在指定的 URL 模式下可用。

And enable @ServletComponentScanon a base class:

@ServletComponentScan在基类上启用:

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

Please note that @ServletComponentScanwill work only with embedded server:

请注意,@ServletComponentScan仅适用于嵌入式服务器:

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

启用对 Servlet 组件(过滤器、servlet 和侦听器)的扫描。仅在使用嵌入式 Web 服务器时才执行扫描。

More info: The @ServletComponentScan Annotation in Spring Boot

更多信息:Spring Boot 中的 @ServletComponentScan 注释

回答by BaiJiFeiLong

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) {
    }
}

回答by cequattro

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