Step-1: Add maven plugin to the eclipse to add the library of the spring framework.
After that make a new maven project and add the dependencies to the POM.xml file like as follows:
4.0.0
com.mail
Mail
0.0.1-SNAPSHOT
war Mail
http://maven.apache.org
UTF-8
org.springframework
spring-webmvc
4.0.1.RELEASE
org.springframework
spring-core
4.0.1.RELEASE
org.codehaus.jackson
jackson-core-asl
1.9.13
org.codehaus.jackson
jackson-mapper-asl
1.9.13
Hew we have added dependencies for spring-core, spring-mvc and jackson core and jackson mapper library.
Jackson library is for getting the data without view, like in json.
Step-2: Define dispatcher servlet for handling the request in spring like as follows in web.xml file
MailRest2
org.springframework.web.servlet.DispatcherServlet
1
mail
/*
Step-3: Make a new spring servlet file in parellel to web.xml file in which name will be based on the dispatcher servlet defined in the web.xml like mail-servlet.xml.
In this component scan package should be the package name of controller class.
And use tag for showing the data in response body.
Step-4 : Create the controller class under the com package here , because we have declared the package come in servlet xml file.
package com;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(“/”)
public class MailController {
@RequestMapping(value = “/getVersion”, method = RequestMethod.GET)
public @ResponseBody Response getVersion(){
Response response = new Response();
response.setSpecVersion(“34c”);
Status status = new Status();
status.setCode(100);
status.setMnemo(“OK”);
response.setStatus(status);
return response;
}
}
package com;
public class Response {
String specVersion;
Status status;
public String getSpecVersion() {
return specVersion;
}
public void setSpecVersion(String specVersion) {
this.specVersion = specVersion;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
}
package com;
public class Status {
int code;
String mnemo;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMnemo() {
return mnemo;
}
public void setMnemo(String mnemo) {
this.mnemo = mnemo;
}
}
Here we have used annotation @controller which makes it as controller of the framework and @ResponseMapping of class which includes in the path of the URL and @ResponseBody is used to show the data in Json form.
Step-5: Now execute the method get Version of the controller using the following URI after deploying it on tomcat server:
http://localhost:8080/Mail/getVersion