DispatcherServlet and web.xml in Spring Boot

后端 未结 4 1801
死守一世寂寞
死守一世寂寞 2020-12-13 04:43

I\'m currently trying to move my project from Java EE to Spring Boot project. However, i\'ve been stucked and confused on the part with dispatcher servlet and web.xml and it

4条回答
  •  一整个雨季
    2020-12-13 05:21

    Spring-boot prefer annotations over xml based configurations, so in your case instead of using web.xml to configure the servlet, servlet-mapping, filter and filter mapping, you can use annotation based automatic bean creations to register beans.For that you need to :

    • Convert the xml based mappings to annotation based mappings
    • Create beans using @Bean annotations so that spring-boot will automatically take them up during component scan.

    For reference: https://docs.spring.io/spring-boot/docs/current/reference/html/howto-traditional-deployment.html

    • For registering filters and adding filter beans you can create a class annotate it with the @Configuration or @Component annotation and create bean of FilterRegistrationBean to register the filter.You can also create the beans of filter itself there by using @Bean annotation.

    For example, the equivalent of the following xml based filter

    
      SomeUrlFilter
       com.company.SomeUrlFilter
    
    
        SomeUrlFilter
        /url/*
        
           paramName
           paramValue
        
    
    

    The equivalent annotation based will be:

    @Bean
    public FilterRegistrationBean someUrlFilterRegistration() {
    
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(someUrlFilter());
        registration.addUrlPatterns("/url/*");
        registration.addInitParameter("paramName", "paramValue");
        registration.setName("Filter");
        registration.setOrder(1);
        return registration;
    } 
    
    @Bean(name = "someUrlFilter")
    public Filter someUrlFilter() {
        return new SomeUrlFilter();
    }
    
    • Springboot still allows us to use the xml based configurations for example if you want to use the web.xml .For example :

    Web.xml

    
        dispatcher
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            /WEB-INF/spring/dispatcher.xml
        
        1
    
    
    
        dispatcher
        /
    
    

    and in another file dispatcher.xml you can create beans as :

    
    
        
    
        
            
            
        
    
    

    Note that Spring web.xml will usually live in src/main/webapp/WEB-INF.

    You can refer : https://www.baeldung.com/register-servlet

提交回复
热议问题