Use of Servlet Annotation with Spring MVC

Hello Java geekier, Today I am going to tell you How to use Servlet Annotation with Spring MVC. In my current project, I have to integrate Spring MVC with Servlet container project. But due to DispacherServlet in web.xml, I was unable to make another Servlet or Filter in my project.

See More:
Biggest Bugs of Spring Web Application
Today many of Java developers work on Spring Web Application...

We can use @WebServlet annotation in SpringBoot to create Servlet. But we can not use it that easy with Spring MVC. And in this tutorial, I found a solution if you also want same. So let’s be with us.

Let’s see an example of how to use a Filter and Servlet Annotation with Spring MVC

Project Directory for Servlet Annotation with Spring MVC

First of all, check the project directory which we’ll follow:

Project Directory for Servlet Annotation with Spring MVC
Project Directory for Servlet Annotation with Spring MVC

Source Code

Create Web Configuration Class

package co.tellmehow.config


import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@EnableWebMvc
@Configuration
@ComponentScan("co.tellmehow.controller")
public class ApplicationWebConfig {

}

In this class, we’ve to add some annotation like

@EnableWebMVC

@EnableWebMvc is equivalent to <mvc:annotation-driven /> in XML. It enables support for @Controller-annotated classes that use @RequestMapping to map incoming requests to a certain method.

[tmh_article_ads]

@Configuration

Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions.

@ComponentScan

Spring needs to know the packages to scan for annotated components. We can use @ComponentScan annotation to specify the base packages to scan. For this project I use co.tellmehow.controller where all controller defined.

Create Application Initializer class

package co.tellmehow.config


import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class ApplicationInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
  
  @Override
    protected Class<?>[] getRootConfigClasses () {
        return null;
    }
    
    @Override
    protected Class<?>[] getServletConfigClasses () {
        return new Class<?>[]{ApplicationWebConfig.class};
    }

    @Override
    protected String[] getServletMappings () {
        return new String[]{"/"};
    }

}

We’ve to extend AbstractAnnotationConfigDispatcherServletInitializer class which is used when an application context hierarchy is not required, applications may return all configuration via getRootConfigClasses() and return null from getServletConfigClasses().

Implementations are required to implement:

Our configuration part is finished now. Now let’s create a Controller and check its running or not.

Create a Controller Class

package co.tellmehow.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller

public class MyController {
    
    @RequestMapping("/myController")
    @ResponseBody
    public String handleRequest () {
        System.out.println("-- handling request in controller --");
        return "Tell Me How: MyController running now";
    }
  
  
  
  
}

I don’t think to elaborate this class to our Spring Developers. If you want then ask me in the comment section.

An output of this class would be:

Output: Use Servlet Annotation with Spring MVC
Output: Use Servlet Annotation with Spring MVC

Now let’s create Servlet and Filter Class

Servlet class

package co.tellmehow.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "myServlet", urlPatterns = "/myServlet")
public class MyServlet extends HttpServlet {

    
  private static final long serialVersionUID = 7088410241741084414L;

  @Override
    protected void doGet (HttpServletRequest req,
                          HttpServletResponse resp)
              throws ServletException, IOException {
    
        System.out.println("-- In MyServlet --");
        PrintWriter writer = resp.getWriter();
        writer.println("Tell Me How: MyServlet running now");
    }
}

An output of Servlet class

Output: Use Servlet Annotation with Spring MVC
Output: Use Servlet Annotation with Spring MVC

Filter Class

package co.tellmehow.servlet;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(filterName = "myFilter", urlPatterns = "/*")
public class MyFilter implements Filter {
    
    @Override
    public void init (FilterConfig filterConfig) throws ServletException {
    }
    
    @Override
    public void doFilter (ServletRequest request, ServletResponse response,
                          FilterChain chain)
              throws IOException, ServletException {
        System.out.println("-- In MyFilter --");
        HttpServletRequest req = (HttpServletRequest) request;
        System.out.println("URI: " + req.getRequestURI());
        chain.doFilter(request, response);
    }
    
    @Override
    public void destroy () {
    }
}

If it helps for you then please comment us.

 

By Tell Me How

It is a technology blog and admin has excellent experience in programming from 5+ year. You can contact us at ceo.tellmehow@gmail.com

Share your thoughts

Leave a Reply

Loading Facebook Comments ...
Loading Disqus Comments ...