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
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.0.1.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency>
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; @EnableWebMvc @Configuration @ComponentScan(basePackages = { "com.mycompany.myproject.web.controller" }) public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } @Bean public InternalResourceViewResolver jspViewResolver() { InternalResourceViewResolver bean = new InternalResourceViewResolver(); bean.setPrefix("/WEB-INF/views/"); bean.setSuffix(".jsp"); return bean; } @Bean(name = "multipartResolver") public CommonsMultipartResolver getMultipartResolver() { return new CommonsMultipartResolver(); } @Bean(name = "messageSource") public ReloadableResourceBundleMessageSource getMessageSource() { ReloadableResourceBundleMessageSource resource = new ReloadableResourceBundleMessageSource(); resource.setBasename("classpath:messages"); resource.setDefaultEncoding("UTF-8"); 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:
tomcat.apache.org/whichversion
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 { @Override 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(); dispatcherServlet.register(MvcConfig.class); // Register and map the dispatcher servlet ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/"); } }
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"> <legend> <spring:message code="table.user.title" /> </legend> <div> <table id="dataTable" class="table table-striped table-bordered"> <thead> <tr> <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> </tr> <thead> <tbody> <c:forEach var="u" items="${usersModel}"> <tr> <td>${u.id}</td> <td>${u.firstName}</td> <td>${u.familyName}</td> <td>${u.email}</td> <tr> </c:forEach> </tbody> </table> </div> </div>
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.*; @Controller public class UserController { @Autowired 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.
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin>
- Test display users
http://localhost:8080/myproject/users
-
Test rest web service
http://localhost:8080/myproject/usersList
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.
Thank you!! finally i managed to use JavaConfig! do you have any example with mongoDB?
Good Explanation and very very complete example.
Thanks again!
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;
}
}
Missing artifact javax.servlet:servlet-api:jar:3.0.1, how to solve this?
Good Job Done! A clean way, Qasim, you can set this in your pom.xml
——
javax.servlet
javax.servlet-api
3.1.0
provided
Cheers!
Very enjoyable project, simple to work with and clean.
Thanks for the great help.
Your friend
Mike
Software Developer
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.
Regards
Manoj
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
thanks for sharing this information it’s very interesting .we are offering spring online training ..if any body want to learn spring plz visit the bellow link…SPRING ONLINE TRAINING
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.
Thanks for sharing. This article helps me a lot. Um… forgive my poor english~~~
how to get the source code.. Can we directly import to maven project using SCM connectors??
Thanks,
You can get source code from Github: https://github.com/samer-abdelkafi/project4example8
Regards.
i can’t run it in tomcat server ??
Can you provide more details: tomcat version, stack trace …
Which tomcat version you work. It doesn’t work on my side.
This project sample uses Tomcat v7.0.57.
Project sample resource link is not working 😦
Thank you for your comment. The source code is exported to Github.
I fixed the link: https://github.com/samer-abdelkafi/project4example8
Best regards.