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