By kswaughs | Thursday, December 24, 2015

Spring restful service without web.xml

Spring 3 WebMVC provides a lot of features and makes Spring developers easier to develop several applications like Web applications and REST services. Spring 3.2.10.RELEASE version has more advanced features with Spring annotations where developers need not to define web.xml or any other kind of context xmls.

In this below example, I will show you how to use Spring 3 MVC annotations to develop a RESTful service.

Step 1 : Create a Configuration class that extends WebMvcConfigurerAdapter which is equivalent to spring dispatcher application context xml.

SpringWebConfig
package com.kswaughs.config;

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

@EnableWebMvc 
@Configuration
@ComponentScan({ "com.kswaughs.web" })
public class SpringWebConfig extends WebMvcConfigurerAdapter {
   
}

Step 2 : Create a Spring Web Initializer class that extends AbstractAnnotationConfigDispatcherServletInitializer which is equivalent to web.xml.

SpringWebInitializer
package com.kswaughs.servlet;

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

import com.kswaughs.config.SpringWebConfig;

public class SpringWebInitializer extends
    AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class[] getServletConfigClasses() {
        return new Class[] { SpringWebConfig.class };
    }

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

    @Override
    protected Class[] getRootConfigClasses() {
        return new Class[] {};
    }

}

Step 3 : Create Controller class to serve the rest service requests

UserController
package com.kswaughs.web.controller;

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

import com.kswaughs.web.beans.UserReq;
import com.kswaughs.web.beans.UserResp;

@Controller
@RequestMapping("usersvc")
public class UserController {

    @RequestMapping(value = "get/{id}", method = RequestMethod.GET)
    @ResponseBody
    public UserResp getUser(@PathVariable String id) {

        UserResp resp = new UserResp();
  
        resp.setId(id);
        resp.setStatus("SUCCESS");
        resp.setMessage("GET Method Processed successfully");

        return resp;
    }

    @RequestMapping(value = "add", method = RequestMethod.POST)
    @ResponseBody
    public UserResp addUser(@RequestBody UserReq req) {

        UserResp resp = new UserResp();
  
        resp.setId(req.getId());
        resp.setStatus("SUCCESS");

        StringBuilder msg = new StringBuilder()
            .append("Hi ").append(req.getName())
            .append(", POST method Processed successfully");
  
        resp.setMessage(msg.toString());

        return resp;
    }
}

Step 4 : Create below model objects to convert JSON requests and responses into java objects.

Request Object - UserReq
package com.kswaughs.web.beans;

public class UserReq {
 
    private String id;
 
    private String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("UserReq [id=");
        builder.append(id);
        builder.append(", name=");
        builder.append(name);
        builder.append("]");
        return builder.toString();
    }
}

Response Object - UserResp
package com.kswaughs.web.beans;

public class UserResp {
 
    private String status;
 
    private String id;
 
    private String message;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("UserResp [status=");
        builder.append(status);
        builder.append(", id=");
        builder.append(id);
        builder.append(", message=");
        builder.append(message);
        builder.append("]");
        return builder.toString();
    }
}

Step 5 : Testing the service. Run the maven build and generated the war with name 'spring-rest-1.0' and deployed in Tomcat 7 server.

  
Test 1
operation : get
method : GET
URL : http://localhost:8080/spring_rest-1.0/usersvc/get/12345
Response >>
{
    "message": "GET Method Processed successfully",
    "id": "12345",
    "status": "SUCCESS"
}
Test 2
operation : add
method : POST
URL : http://localhost:8080/spring_rest-1.0/usersvc/add
Request >>
{     
    "id" : "2222", 
    "name" : "kswaughs"    
}

Response >>
{
    "status": "SUCCESS",
    "id": "2222",
    "message": "Hi kswaughs, POST method Processed successfully"
}

Use Below maven dependencies in your pom.xml. In maven war plugin, set failOnMissingWebXml to false, Otherwise maven war plugin will fail to generate WAR when web.xml is not used.

pom.xml
<properties>
    <spring.version>3.2.10.RELEASE</spring.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-core-asl</artifactId>
        <version>1.9.13</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.13</version>
    </dependency>
</dependencies>
<build>
    <defaultGoal>install</defaultGoal>
    <plugins>
        <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.2</version>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
                <archive>
                    <manifestEntries>
                        <Build-Jdk>1.6</Build-Jdk>
                    </manifestEntries>
                </archive>
            </configuration>
        </plugin>
    </plugins>
</build>

Recommend this on


10 comments:

  1. This thing I ll try it out and let you know! Thanks for sharing BTW!

    ReplyDelete
  2. Thanks for sharing this valuable piece of information. Keep sharing more such awesome articles in the future. Goodbye!

    ReplyDelete
  3. It is mostly Healthrite Cloud Nine Slippers used in refrigeration and aerospace and might possess strength like that of steel. Where relevant, you'll be able to|you presumably can} see country-specific product info, presents, and pricing. With more than 200 years of combined expertise, our team of pros are experts of their craft. Our staff stay with us for the long haul, gaining valuable expertise each and every yr.

    ReplyDelete