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.
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.
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
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.
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(); } }
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.
<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>
ReplyDeleteI got lot of ideas after reading this. Share more as similar to this. Thank you for shared this.
core java training in chennai
core java classes
core javaTraining in Tambaram
c c++ courses in chennai
C Language Training
javascript training in chennai
Appium Training in Chennai
JMeter Training in Chennai
Nice blog!! I hope you will share more info like this. I will use this for my studies and research.
ReplyDeleteAngularjs Training in Chennai
Angularjs Course in Chennai
Ethical Hacking Course in Chennai
Tally Course in Chennai
gst training in chennai
salesforce training institute in chennai
Angularjs Certification in Chennai
Angularjs Training in Chennai
Angularjs Course in Chennai
Excellent post. Thanks a lot to the author of this post for sharing this with us.
ReplyDeleteIELTS Coaching in Mulund
IELTS Training in Mulund West
IELTS Courses in Mulund
IELTS Coaching Centres in Mulund
Spoken English Class in Chennai
Spoken English in Chennai
IELTS Coaching in Chennai
Such a wonderful post, Your explanation way is too good and this is very easy to understand with depth content. Kindly updating for me.
ReplyDeleteCorporate Training in Chennai
Corporate Training Companies in Chennai
Oracle DBA Training in Chennai
Embedded System Course Chennai
Power BI Training in Chennai
Linux Training in Chennai
Oracle Training in Chennai
Tableau Training in Chennai
Unix Training in Chennai
Excel Training in Chennai
apental calc apk
ReplyDeletevumoo
ReplyDeleteWell written Blog, I really enjoy reading your blog. this info will be helpful for me. Thanks for sharing. keep tup
ReplyDeleteAi & Artificial Intelligence Course in Chennai
PHP Training in Chennai
Ethical Hacking Course in Chennai Blue Prism Training in Chennai
UiPath Training in Chennai
This thing I ll try it out and let you know! Thanks for sharing BTW!
ReplyDeleteThanks for sharing this valuable piece of information. Keep sharing more such awesome articles in the future. Goodbye!
ReplyDeleteIt 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¡Gran artículo sobre servicios RESTful en Spring! He probado algo similar en mi blog, pero con enfoque en aplicaciones móviles. ¿Has considerado integrarlo con archivos mobile apk? ¡Saludos!
ReplyDeletethe Spring RESTful service without web.xml. It really simplifies things! Have you considered using apk mod for better flexibility? Keep it up!
ReplyDelete