Over a million developers have joined DZone.

How to Make a Web Service with Spring MVC and Test with Spring Test Framework

DZone's Guide to

How to Make a Web Service with Spring MVC and Test with Spring Test Framework

· DevOps Zone
Free Resource

The Nexus Suite is uniquely architected for a DevOps native world and creates value early in the development pipeline, provides precise contextual controls at every phase, and accelerates DevOps innovation with automation you can trust. Read how in this ebook.

This is a very basic example of using Spring MVC, REST and the Spring Test Framework using Spring’s Java configuration.

The first part of this is to create a configuration class for the web app. Below is a sample of the configuration class we are going to use:

@ComponentScan(basePackages = {"com.johnathanmsmith.mvc.web"})
public class WebMVCConfig extends WebMvcConfigurerAdapter

    private static final Logger logger = LoggerFactory.getLogger(WebMVCConfig.class);

    public ViewResolver resolver()
        UrlBasedViewResolver url = new UrlBasedViewResolver();
        return url;

    public void addResourceHandlers(ResourceHandlerRegistry registry)
        logger.debug("setting up resource handlers");

    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)

    public SimpleMappingExceptionResolver simpleMappingExceptionResolver()
        SimpleMappingExceptionResolver b = new SimpleMappingExceptionResolver();

        Properties mappings = new Properties();
        mappings.put("org.springframework.web.servlet.PageNotFound", "p404");
        mappings.put("org.springframework.dao.DataAccessException", "dataAccessFailure");
        mappings.put("org.springframework.transaction.TransactionException", "dataAccessFailure");
        return b;

Next you have to setup the web.xml file to use the above configuration class. We do this by setting the contectConfigLocation to the package of the configuration class. See below:

<web-app 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"

        <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
            <param-value>com.johnathanmsmith.mvc.web.config, com.johnathanmsmith.mvc.web.controller</param-value>

        <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>

Now lets setup a basic controller to display a page:

class JSonController

    private static final Logger logger = LoggerFactory.getLogger(JSonController.class);
    @RequestMapping(value = "/{name}", method = RequestMethod.GET)
    public User getName(@PathVariable String name, ModelMap model) throws ResourceNotFoundException

        logger.debug("I am in the controller and got user name: " + name);


            Simulate a successful lookup for 2 users, this is where your real lookup code would go


        if ("JohnathanMarkSmith".equals(name))
            return new User("Johnathan Mark Smith", name);

        if ("Regan".equals(name))
            return new User("Regan Smith", name);

        throw new ResourceNotFoundException("User Is Not Found");

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ResponseEntity<User> getDisplayDefault(ModelMap model)
        return new ResponseEntity<User>(new User("Johnathan Mark Smith", "JohnathanMarkSmith"), HttpStatus.OK);

    public ResponseEntity<ErrorHolder> handle(ResourceNotFoundException e)
        logger.warn("The resource was not found", e);
        return new ResponseEntity<ErrorHolder>(new ErrorHolder("The resource was not found"), HttpStatus.NOT_FOUND);


Testing Your Web Service

Below you will see the Spring Test Framework and how to tell your web server with it

@ContextConfiguration(classes = {WebMVCConfiguration.class})
public class TestHelloWorldWeb
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    public void setup()
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();

    public void getFoo() throws Exception
            This following code will do 'GET' to the web apps
            and also that it has a attribute "user" to "JohnathanMarkSmith"

                .andExpect(jsonPath("$.user").value("Johnathan Mark Smith"));

That's all it takes.

Getting The Project and Running It

To get this project and run it you will need to follow the following steps:

git clone  git@github.com:JohnathanMarkSmith/springmvc-rest-test.git
cd springmvc-rest-test/
mvn tomcat7:run

Now open your web brower and goto

This its… Have run with it…

If you have any questions or comments please email me at john@johnathanmarksmith.com

The DevOps Zone is brought to you in partnership with Sonatype Nexus.  See how the Nexus platform infuses precise open source component intelligence into the DevOps pipeline early, everywhere, and at scale. Read how in this ebook


Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}