Spring-boot prefers annotations over xml- based configurations, so in your case, instead of using web.xml to configure servlet, servlet-mapping, filter and filter mapping you can use the automatic creation of annotation-based bean components to register bean components. To do this, you need to:
- Convert XML based mappings to annotation mappings
- Create bean components using
@Bean annotations @Bean that spring-boot automatically @Bean them when scanning components.
For reference: https://docs.spring.io/spring-boot/docs/current/reference/html/howto-traditional-deployment.html.
- To register filters and add filtering components, you can create a class, annotate it with the
@Configuration or @Component and create a @Component bean to register the filter. You can also create filter beans yourself using the @Bean annotation.
For example, the equivalent of the following xml filter
<filter> <filter-name>SomeUrlFilter</filter-name> <filter-class>com.company.SomeUrlFilter</filter-class> </filter> <filter-mapping> <filter-name>SomeUrlFilter</filter-name> <url-pattern>/url/*</url-pattern> <init-param> <param-name>paramName</param-name> <param-value>paramValue</param-value> </init-param> </filter-mapping>
An equivalent annotation based on would 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 xml-based configurations, for example, if you want to use
web.xml . For example:
web.xml
<servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/dispatcher.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
and in another dispatcher.xml file you can create beans as:
<beans ...> <context:component-scan base-package="com.demo"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
Note that Spring web.xml will usually be web.xml in src/main/webapp/WEB-INF .
You can contact: https://www.baeldung.com/register-servlet
Ananthapadmanabhan
source share