Spring MVC – Full java based config

Spring MCV is a very powerful and flexible framework for web application development.

It doesn’t just implement the MVC pattern, it allows you to develop Rest web services.


This post presents a web project sample with a full java configuration using Spring MVC 4 and Servlet 3 api. The source code is available in this link.

This project implements client side for the persistence sample presented in Spring-Data-JPA article

1 – Add project dependencies


2 – Spring MVC config class

import org.springframework.context.annotation.*;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@ComponentScan(basePackages = { "com.mycompany.myproject.web.controller" })
public class MvcConfig extends WebMvcConfigurerAdapter {

    public void addResourceHandlers(ResourceHandlerRegistry registry) {

    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {

    public InternalResourceViewResolver jspViewResolver() {
        InternalResourceViewResolver bean = new InternalResourceViewResolver();
        return bean;

    @Bean(name = "multipartResolver")
    public CommonsMultipartResolver getMultipartResolver() {
        return new CommonsMultipartResolver();

    @Bean(name = "messageSource")
    public ReloadableResourceBundleMessageSource getMessageSource() {
        ReloadableResourceBundleMessageSource resource = new ReloadableResourceBundleMessageSource();
        return resource;


3 – Webapp initializer

With servlet 3 API you can use a class to configure your web project instead of the classic web.xml file.
You have to check if your application server or your servlet container supports servlet 3 spec. For Tomcat you can have this information in this link:

import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.DispatcherServlet;

public class WebAppInitializer implements WebApplicationInitializer {

    public void onStartup(ServletContext container) {
        // Create the 'root' Spring application context
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(ServiceConfig.class, JPAConfig.class, SecurityConfig.class);

        // Manage the lifecycle of the root application context
        container.addListener(new ContextLoaderListener(rootContext));

        // Create the dispatcher servlet's Spring application context
        AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
        // Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet));


4 – Model class.

public class User {
    private Long id;

    private String firstName;

    private String familyName;

    private String email;

    // add extra attributes
    // add getters and setters

5 – Add view as jsp page
We create a usersView.jsp page with code source bellow to display users list.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<div class="col-sm-offset-1 col-sm-10">

        <spring:message code="table.user.title" />

        <table id="dataTable" class="table table-striped table-bordered">
                    <th><spring:message code="table.user.id" /></th>
                    <th><spring:message code="table.user.firstName" /></th>
                    <th><spring:message code="table.user.falilyName" /></th>
                    <th><spring:message code="table.user.email" /></th>
                <c:forEach var="u" items="${usersModel}">

6 – Develop your controller

The @Controller annotation indicates that a particular class serves the role of a controller.
The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

public class UserController {

    private UserService userService;
    * Request mapping for user
    @RequestMapping(value = "users", method = RequestMethod.GET)
    public ModelAndView getUsersView() {
        ModelAndView mv= new ModelAndView("usersView");
        mv.addObject("usersModel", userService.findAll());
        return mv;
    * Rest web service
    @RequestMapping(value = "/usersList", method = RequestMethod.GET)
    public @ResponseBody List<UserDto> getUsersRest() {
        return userService.findAll();

7 – Test web project
When building your project you may have maven error telling you that the web.xml file is missing.
You can fix it by configuring the maven war plugin as presented bellow.


  • Test display users

  • Test rest web service
    You will get json reponse.

            "id": 1,
            "firstName": "adminName",
            "familyName": "adminFamily",
            "email": "admin@maycompany.com",
            "phone": "0033 1 23 45 67 89",
            "language": "en",
            "login": "admin",
            "password": "admin",
            "burthDate": null,
            "authorities": [
                {"id": 3, "name": "user"},
                {"id": 2, "name": "technical user"},
                {"id": 1, "name": "admin"}
            "enabled": true,
            "pictureId": null,
            "authoritiesAsString": "user, technical user, admin"

Here’s the how to video created by Webucator.com. Check out their Spring training classes.

18 thoughts on “Spring MVC – Full java based config

  1. Pingback: Why the compiler says ServletContext has no the 'addListener' and 'addServlet' methods

  2. Pingback: A very good post on Spring java configuration | Altar Moss

    • I reply myself with this mongoconfig i have managed:

      import org.springframework.context.annotation.Bean;
      import org.springframework.data.mongodb.MongoDbFactory;
      import org.springframework.data.mongodb.core.MongoTemplate;
      import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
      import com.mongodb.MongoClient;

      public class MongoConfiguration {

      public @Bean
      MongoDbFactory mongoDbFactory() throws Exception {
      return new SimpleMongoDbFactory(new MongoClient(), “yourdb”);

      public @Bean
      MongoTemplate mongoTemplate() throws Exception {
      MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
      return mongoTemplate;

  3. Nice blog written on “Spring MVC”. The info. Contained in the blog is very helpful for Java developers. Here is an another informative blog from FindNerd community on Spring MVC & MongoDB http://findnerd.com/list/view/Spring-MVC-and-MongoDB/2240/ , hope this will help developers too. FindNerd community is also an awesome place for developers to post & view java questions and answers to enhance the tech knowledge among the developers community.


  4. I can’t seem to find servletRegistration.Dynamic in my java 8. pls what do you think is the problem… its making me switch back to xml configuration

  5. the problem with stuff like Spring is most tutorials are outdated, documentation is very complicated to put in pratice. I usually completely ignore the documentation and skip directly to blogs like these.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s