DispatcherServlet and web.xml in Spring Boot
Asked Answered
S

4

41

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 seems like web.xml is no longer being read by the project anymore. The current project is running on tomcat 7.

In my web.xml file, I have lots of servlet, servlet-mapping, filter and filter mapping and I don't really understand how to do the mapping in the dispatcher.

I've attached a sample of my web.xml below and the version is 2.5.

<?xml version="1.0" encoding="UTF-8"?>
<web-app metadata-complete="true" version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name>displayName</display-name>
  <description>description</description>
  <resource-ref>
    ...
  </resource-ref>
  <filter>
    <filter-name>Some Filter Name</filter-name>
    <filter-class>Some Filter Class</filter-class>
    <init-param>
      <param-name>Some Param Name</param-name>
      <param-value>Some Value</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>Some Filter Name</filter-name>
    <url-pattern>Some url-pattern</url-pattern>
  </filter-mapping>
  <context-param>
    <param-name>Some Param Name</param-name>
    <param-value>Some Param Value</param-value>
  </context-param>
  <servlet>
    <servlet-name>Some Servlet Name</servlet-name>
    <servlet-class>Some Servlet Class</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Some Servlet Name</servlet-name>
    <url-pattern>Some Url Pattern</url-pattern>
  </servlet-mapping>
</web-app>

Qns:

  1. Should I convert all the stuff in my web.xml to rely on the spring dispatcher, if yes how can I achieve that?
  2. Is moving away from the web.xml the way to go for spring boot project?

Can anyone please guide me along here? Thanks!!

Slyke answered 5/4, 2017 at 8:15 Comment(0)
S
33
  1. Yes, spring boot no longer relies on xml configuration and it configures an equivalent to the dispatcher servlet automatically. You can follow the following link to see how to register your filters: How to add a filter class in Spring Boot?
  2. If you use maven and not gradle, the only XML in your spring boot project should be pom.xml. The way to go with spring boot is moving all your xml configuration, web.xml etc to spring boot's auto configuration + your java configuration.

Spring boot works very good when you do everything in java configuration and follow its principals. From my experience with it, when you start merging XML configuration and the legacy spring it starts breaking the auto configuration process and its much better to try as much as you can to comply with the new spring boot best practices.

Sassan answered 5/4, 2017 at 8:26 Comment(2)
Thanks for clarifying that! So am I right to say that I would need to register all the values from each of the tags in the web.xml to my @SpringBootApplication class?Slyke
It is better to keep the @SpringBootApplication class clean. create a new package under the package of your @SpringBootApplication called config for example and create a @Configuration annotated class called FiltersConfiguration for example and start registering your filters as @Bean annotated methods. This way your code will be cleaner and easier to read. You can create more @Configuration classes as needed.Sassan
P
11
  1. You can keep your web.xml, but it needs to add

    <listener>
         <listener-class>org.springframework.boot.legacy.context.web.SpringBootContextLoaderListener</listener-class>
    </listener> 
    

    in web.xml. And, required dependency of pom.xml.

  2. All listener classes, filters converts in Java class. This class would be @Configuration.

  3. If you have an interceptor, that can be moved to configuration class.

Phidippides answered 31/10, 2017 at 5:35 Comment(0)
M
8

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

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

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

<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 file dispatcher.xml 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 live in src/main/webapp/WEB-INF.

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

Mullah answered 16/4, 2019 at 6:3 Comment(0)
B
1

Spent quite some time so sharing three things I remember to make it working from command line.

  1. Most important: JSPs should be kept only in folder /src/main/resources/META-INF/resources. more info here
  2. Make sure that maven while building jar is considering your folders /src/main/resources, otherwise add these lines in your pom.xml

  <resources>
     <resource>
        <directory>src/main/resources</directory>   
      </resource>
    </resources>
  1. In your mvc config file

    @Configuration
    public class MvcConfig extends WebMvcConfigurerAdapter {
        @Bean
        public InternalResourceViewResolver viewResolver(){
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/Representation/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
    
Biz answered 2/6, 2019 at 1:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.