Building restful services with spring MVC 4

Source: Internet
Author: User
Tags apache tomcat

Building restful services with Spring MVC 4 has many advantages over other frameworks. First, Spring MVC 4 is one of the spring's frameworks that can be well integrated with spring. Second,the Spring MVC 4 Interceptor is interception at the method level, which is more efficient than the interceptors of other MVC frameworks (such as Struts2). In addition, Spring MVC 4 uses annotation-based configuration for easy and flexible development.


Spring MVC 4 uses the Jacson parsing JSON. Jacson is a highly efficient and powerful JSON tool class that makes it easy to serialize and deserialize between Java objects and JSON objects and XML documents. The examples in this article are the spring 4.1.1.RELEASE and Jacson 2.4.0, tested without any abnormalities. Next, the Dry goods:


Development environment Preparation:

Eclipse Luna

Apache Tomcat 8.0

JDK 1.7

Spring 4.1.1.RELEASE

Jackson 2.4.0


The project catalog is as follows:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/53/69/wKioL1RmtujyFDVPAAGhvKmuW54452.jpg "title=" Category.png "width=" 324 "height=" "border=" 0 "hspace=" 0 "vspace=" 0 "style=" width:324px;height:400px; "alt=" Wkiol1rmtujyfdvpaaghvkmuw54452.jpg "/>



1. Create a new Maven Project, select " archetype type" and select "Maven-archetype-webapp".


     2. Add   maven 


Spring's MAVEN warehouse address:http://repo1.maven.org/maven2/org/springframework/

Jackson's MAVEN warehouse address:http://repo1.maven.org/maven2/com/fasterxml/jackson/core/



<project xmlns= "http://maven.apache.org/POM/4.0.0"  xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "  xsi:schemalocation=" http://maven.apache.org/POM/4.0.0 http:// Maven.apache.org/maven-v4_0_0.xsd ">  <modelVersion>4.0.0</modelVersion>   <groupid>com.favccxx.favsoft</groupid>  <artifactid>favspringmvcrestful</ artifactid>  <packaging>war</packaging>  <version>0.0.1-snapshot</ Version>  <name>favspringmvcrestful maven webapp</name>  <url >http://maven.apache.org</url>    <properties>  < spring.version>4.1.1.release</spring.version>  <jackson.version>2.4.0</ jackson.version>  </properties>    <dependencies>     <dependency>      <grOupid>junit</groupid>      <artifactid>junit</artifactid>       <version>3.8.1</version>       <scope>test</scope>    </dependency>         <dependency><groupid>org.springframework</groupid><artifactid>spring-core </artifactId><version>${spring.version}</version></dependency><dependency>< Groupid>org.springframework</groupid><artifactid>spring-webmvc</artifactid><version >${spring.version}</version></dependency><dependency><groupid>org.springframework </groupid><artifactid>spring-beans</artifactid><version>${spring.version}</version ></dependency><dependency><groupId>org.springframework</groupId><artifactId> Spring-context</artifactid><version>${spring.version}</version></dependency><dependency>  < Groupid>com.fasterxml.jackson.core</groupid>  <artifactid>jackson-core</artifactid >  <version>${jackson.version}</version></dependency><dependency>   <groupId>com.fasterxml.jackson.core</groupId>  <artifactId> jackson-annotations</artifactid>  <version>${jackson.version}</version></ dependency><dependency>  <groupid>com.fasterxml.jackson.core</groupid>   <artifactid>jackson-databind</artifactid>  <version>${jackson.version}</ version></dependency><dependency><groupid>jstl</groupid><artifactid>jstl</ Artifactid><version>1.2</version></dependency><dependency><groupid>taglibs </groupid><artifactid>standard</artifactId><version>1.1.2</version></dependency>       </dependencies>  <build>    <finalName>favspringmvcrestful< /finalname>  </build></project>


3. in Web. XML, configure Dispatcherservlet forwarding and encoding for Spring MVC 4.

<?xml version= "1.0"  encoding= "UTF-8"? ><web-app version= "2.4"  xmlns= "/http Java.sun.com/xml/ns/j2ee "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation="/HTTP/ Java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd "><display-name>favblog </display-name><context-param><param-name>contextConfigLocation</param-name>< param-value></param-value></context-param><filter><filter-name>encodingfilter</ Filter-name><filter-class>org.springframework.web.filter.characterencodingfilter</filter-class> <init-param><param-name>encoding</param-name><param-value>UTF-8</param-value> </init-param><init-param><param-name>forceencoding</param-name><param-value>true </param-value></init-param></filter><filter-mapping><filter-name>encodingfilter </filter-name><url-patteRn>/*</url-pattern></filter-mapping><listener><listener-class> Org.springframework.web.context.contextloaderlistener</listener-class></listener><servlet> <servlet-name>springMVC</servlet-name><servlet-class> Org.springframework.web.servlet.dispatcherservlet</servlet-class><init-param><param-name> Contextconfiglocation</param-name><param-value>classpath*:spring-context.xml</param-value> </init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping>< Servlet-name>springmvc</servlet-name><url-pattern>/</url-pattern></servlet-mapping> </web-app>
<?xml version= "1.0"  encoding= "UTF-8"? ><beans xmlns= "http://www.springframework.org/ Schema/beans "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xmlns:context="/HTTP/ Www.springframework.org/schema/context "xmlns:mvc=" Http://www.springframework.org/schema/mvc "xsi:schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/ context/spring-context-4.1.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/ Schema/mvc/spring-mvc-4.1.xsd "><context:component-scan base-package=" Com.favccxx.favsoft.favjson.controller "></context:component-scan><mvc:annotation-driven></ Mvc:annotation-driven>    <bean id= "Viewresolver"  class= " Org.springframework.web.servlet.view.UrlBasedViewResolver "&GT;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBsp;<property name= "Viewclass"              Value= "Org.springframework.web.servlet.view.JstlView"  />         <property name= "prefix"  value= "/web-inf/views"  />         <property name= "suffix"  value= ". JSP"  />    </ Bean></beans>


4. Create a new Favuser.java class to test the mapping between JSON and object. It is important to note that if you want to format dates, you can use @JsonFormat on their getter methods to output dates that match the pattern type. However, this also requires that the date parameter entered must also be of type pattern.

package com.favccxx.favsoft.favjson.pojo;import java.util.date;import  com.fasterxml.jackson.annotation.jsonformat;public class favuser {private string  userid;private string username;private int userage;private date createdate; Public string getuserid ()  {return userid;} Public void setuserid (String userid)  {this.userid = userid;} Public string getusername ()  {return username;} Public void setusername (String username)  {this.username = username;} Public int getuserage ()  {return userage;} Public void setuserage (Int userage)  {this.userage = userage;} @JsonFormat (pattern= "Yyyy-mm-dd hh:mm:ss") public date getcreatedate ()  {return  CreateDate;} Public void setcreatedate (Date createdate)  {this.createdate = createdate;}}


5. Create a new Favrestfulcontroller and test Spring MVC 4 with a different method to return a string, object-type JSON.

package com.favccxx.favsoft.favjson.controller;import java.io.ioexception;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.requestparam;import  org.springframework.web.bind.annotation.restcontroller;import  com.fasterxml.jackson.core.jsonparseexception;import com.fasterxml.jackson.databind.jsonmappingexception; import com.fasterxml.jackson.databind.objectmapper;import com.favccxx.favsoft.favjson.pojo.favuser;@ restcontrollerpublic class favrestfulcontroller {@RequestMapping (value= "/getusername", method= Requestmethod.post) Public string getusername (@RequestParam (value= "name")  string name) { Return name;} @RequestMapping ("Getfavuser") Public favuser getfavuser (@RequestParam ("UserName")  String  Username,string userid,int userage) {favuser favuser = new favuser (); FavUser.setUserId (userId); Favuser.setusername (UserName); Favuser.setuserage (userage); return favuser;} @RequestMapping ("Getfavuserbody") public favuser getfavuserbody (@RequestBody  string body) { Objectmapper mapper = new objectmapper (); Favuser favuser = null;try {favuser = mapper.readvalue (body,   Favuser.class);}  catch  (jsonparseexception e)  {e.printstacktrace ();}  catch  (jsonmappingexception e)  {e.printstacktrace ();}  catch  (ioexception e)  {e.printstacktrace ();} Return favuser;}}


6. The results of the operation are as follows:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/53/69/wKioL1RmuWjhdcagAAEnFQ-0h9k100.jpg "title=" Rest-param.png "alt=" Wkiol1rmuwjhdcagaaenfq-0h9k100.jpg "/>

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/53/6B/wKiom1RmuPeR_IPQAAHCrDPrp7Y273.jpg "title=" Restresult.png "alt=" Wkiom1rmuper_ipqaahcrdprp7y273.jpg "/>


This article is from the "Dust Wind with the Sky" blog, please be sure to keep this source http://favccxx.blog.51cto.com/2890523/1576730

Building restful services with spring MVC 4

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.