IT TIP

Spring Boot에 보조 서블릿을 등록하려면 어떻게해야합니까?

itqueen 2020. 11. 25. 21:46
반응형

Spring Boot에 보조 서블릿을 등록하려면 어떻게해야합니까?


내 애플리케이션에 등록해야하는 추가 서블릿이 있습니다. 그러나 Spring Boot와 Java Config를 사용하면 web.xml파일에 서블릿 매핑을 추가 할 수 없습니다 .

추가 서블릿을 어떻게 추가 할 수 있습니까?


서블릿에 대한 빈을 추가하십시오 . 에 매핑됩니다 /{beanName}/.

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

또한 사용할 수 있습니다 ServletRegistrationBean

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

결국 내가 취한 길이되었습니다.


Application 클래스에서 @Bean과 같이 다른 ServletRegistrationBean으로 여러 개의 다른 서블릿을 등록 할 수 있으며 여러 서블릿 매핑이있는 서블릿을 등록 할 수 있습니다.

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

다음과 같이 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);
  }
}

임베디드 서버를 사용하는 경우 @WebServlet서블릿 클래스로 주석을 달 수 있습니다 .

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

에서 @WebServlet :

서블릿을 선언하는 데 사용되는 주석입니다.

이 어노테이션은 배치시 컨테이너에 의해 처리되며 해당 서블릿은 지정된 URL 패턴에서 사용 가능합니다.

그리고 @ServletComponentScan기본 클래스에서 활성화하십시오 .

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

있습니다 @ServletComponentScan가 포함 된 서버에서만 작동합니다 :

서블릿 구성 요소 (필터, 서블릿 및 리스너)에 대한 스캔을 활성화합니다. 내장 웹 서버를 사용하는 경우에만 스캔이 수행됩니다.

더 많은 정보 : Spring Boot의 @ServletComponentScan 주석


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

이 방법은 WS01455501EndpointFor89라는 서블릿을 가지고 나를 위해 일했습니다.

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

참고 URL : https://stackoverflow.com/questions/20915528/how-can-i-register-a-secondary-servlet-with-spring-boot

반응형