Spring MVC Rest Learning II

Source: Internet
Author: User

1, controller should be the core of SPRINGMVC , controller to learn the annotations are many, but the role of these annotations in the program is really not to be underestimated, to see the list of these items:

@Controller: Define a class as a controller, and this is a bit like @Repository

@RequestMapping: Define URL mappings for a controller and request method

@PathVariable: Define path parameters, rest itself is a unique definition of the resource, the use of parameters in the URL is also a unique definition of a form

@ResponseBody: Defines the return result, which is particularly useful when Ajax requests, because there is no need to jump to another URL

@ResponseStatus: Define the return status

@RequestParam: Define request parameters, if it is the foreground and background parameter with the same name, then it is not necessary to use it

........................

The controller code is posted below

/** * <p> Project name: restful * <p>package name:com.hnust.controller *  File name:resourcecontroller.java  *  version:1.00  *  Date created: October 26, 2014  *  copyright?2014 hnust . all rights reserved. */package com.hnust.controller;import  org.springframework.beans.factory.annotation.autowired;import org.springframework.stereotype.controller; import org.springframework.ui.modelmap;import org.springframework.util.stringutils;import  org.springframework.web.bind.annotation.pathvariable;import  org.springframework.web.bind.annotation.requestmapping;import  org.springframework.web.bind.annotation.requestmethod;import  org.springframework.web.bind.annotation.responsebody;import com.hnust.bean.message;import  com.hnust.bean.resource;import com.hnust.service.resourceservice;/** * * @author: Heweipo *@ version 1.00 * */@Controller @requestmapping("/resource") public class resourcecontroller {@Autowiredprivate  ResourceService  Service;/** *  * <p> gets the resource by ID  *  uses @pathvariable annotation here, and returns a string, Having SPRINGMVC automatically find the most appropriate view parser  *  advantage is the ability to find the HTML view parser, but the downside is that JavaBean to XML format, *  need to be in the   Org.springframework.oxm.jaxb.Jaxb2Marshaller binding javabean *  So   here resource be sure to bind  * @ param id *  @param  model *  @return   *  @return  String      * author: heweipo */@RequestMapping (value= "/get/{id}"  ,  Method=requestmethod.get) Public string get (@PathVariable ("id")  String id ,  Modelmap model) {model.put ("resource",  service.getresource (ID));return  "Resource";} /** *  * <p> storage Resource, in addition, the number parameter injection about resource is worth noting, if the URL carries the parameters can not be converted to  *  Integer type, then it is impossible to continue accessing this method!! Therefore, for JavaBean it is best to set the data type that corresponds to the database  *  classType constraints.  *  using @responsebody annotations Here, the returned object will be parsed by the corresponding view parser, *  but there will be no HTML parser, but there is a  *  advantage: JavaBean   If you switch to  XML , you don't need to  * org.springframework.oxm.jaxb.jaxb2marshaller in spring-servlet .   Bound  *  @param  resource *  @param  model  *  @return  void      * author: heweipo */@RequestMapping (value= "/put"  ,  Method=requestmethod.put) public  @ResponseBody  message put (resource resource ,  Modelmap model) {message message = new message (); if (Stringutils.isempty (resource.getId ())          | |  stringutils.isempty (Resource.getname ())) {message.setmsg ("Please enter id  and   username") Message.setresult (" Faile "); return message;} Service.insertresource (Resource); Message.setmsg ("Data already stored"); Message.setresult ("Success"); return message;} /** *  * <p> Update via IDresource *  @param  resource *  @param  model *  @return   *  @return  message     * author: heweipo */@RequestMapping (value= "/ Post " , method=requestmethod.post) public  @ResponseBody  message post (resource  Resource , modelmap model) {message message = new message (); Stringutils.isempty (Resource.getid ())) {message.setmsg ("ID cannot be empty"), Message.setresult ("Faile"); return message ;} Service.updateresource (Resource); Message.setmsg ("Data has been modified"); Message.setresult ("Success"); return message;} /** *  * <p> Delete resources by ID  *  @param  id *  @param  model *   @return   *  @return  message     * author: heweipo  */@RequestMapping (value= "/delete/{id}"  , method=requestmethod.delete) public  @ResponseBody  message delete (@PAthvariable ("id") String id, modelmap model) {message message = new message () ; Service.deleteresource (ID); message.setmsg ("Data deleted"); Message.setresult ("Success"); return message;}}

Note A few notes:

1) regarding the request parameter automatic encapsulation problem, when we adopt JavaBean in the method's formal parameter, SPRINGMVC will enclose the request parameter in the JavaBean corresponding attribute as an instance of JavaBean returns, if some attributes have no value, he is empty If the property value is assigned to a type conversion error, the URL cannot be requested. The encapsulated JavaBean instance is stored in the Modelmap, and is used as the key value in the first letter of the JavaBean class name, so you can get Model.get (' resource ') this way; XML parsing requires a root element, so if we store too many elements in our model XML is unresolved. This controller doesn't exist because I'm using @responsebody.

2) questions about the return value,@ResponseBody is the identification of the return value, especially when object parsing is useful. Furthermore, after using the @ResponseBody, the XML parsing object can not be bound in Spring-servlet, however, if we sometimes need to return an HTML, or JSON, or XML, we will not use @ResponseBody, instead, the returned object is stored in the model in the form of a string. When the return value is NULL, the effect is the same as @ResponseBody.

The following is the modified code:

/** * * <p> update via ID resource * Message Be sure to bind in Org.springframework.oxm.jaxb.Jaxb2Marshaller * @param resource * @param Model * @return * @return Message * Author:heweipo */@RequestMapping (value= "/post", Method=requestmethod.post) Publ IC String post (Resource Resource, Modelmap model) {//here remove SPRINGMVC to help us package javabeanmodel.remove ("Resource"); Message message = new Message ();//This stores the javabeanmodel.put we need to parse ("message", message); if (Stringutils.isempty ( Resource.getid ())) {message.setmsg ("ID cannot be null"); Message.setresult ("Faile"); return null;} Service.updateresource (Resource); Message.setmsg ("Data has been modified"); Message.setresult ("Success");// The return null effect is the same as using @responsebody, but the principle is different,//@ResponseBody seems to take the Servlet3.0 asynchronous character return null;}

The corresponding Spring-servlet.xml source code:

<!--XML and Java data Conversion--<bean id= "Jaxbmarshaller" class= "Org.springframework.oxm.jaxb.Jaxb2Marshaller" >& Lt;property name= "Classestobebound" ><list> <!--need to be bound here because the controller does not return with @responsebody--< Value>com.hnust.bean.message</value></list></property> </bean>

2 Request Type

In @requestmapping we assign a value to the method, and if it is assigned then it must be accessed according to the corresponding request, and no person appears 405. Test tools are used in the project:

Tools used: Firefox restclient plug-in https://addons.mozilla.org/zh-CN/firefox/addon/restclient/

1) New resources: Put http://localhost:8080/restful/resource/put?id=id_888&name=ireport&number=89

<message><msg> data has been stored </msg><result>success</result></message>

2) Update Resources post http://localhost:8080/restful/resource/post?id=id_888&name=node.js&number=12

<message><msg> data has been updated </msg><result>success</result></message>

3) Delete the resource delete http://localhost:8080/restful/resource/delete/id_888

<message><msg> Data deleted </msg><result>success</result></message>

3 About returning content formats

The content negotiation mechanism is very simple, there are two ways, one is the view rendering used in the project for content negotiation, the other is the type conversion, the source code in this project is as follows:

  <!--  is mainly for controller  and  URL  annotation bindings, which can be configured for converters: Only the converter can be configured to convert classes to JSON and XML. Of course only for the translator-based negotiation resource presentation  -->  <bean class= " Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter " />        <!-- XML  and  Java  data conversion   -->  <bean  id= "Jaxbmarshaller"  class= "Org.springframework.oxm.jaxb.Jaxb2Marshaller" ><property name= "Classestobebound" ><list><!--common xml  mapping   JavaBean  Registration   --> <value>com.hnust.bean.Resource</value> <!--  does not need to be bound here because the controller uses Responsebody to return  --><!-- <value>com.hnust.bean.message</value>  --></list></ property>  </bean>    <!--  View-based rendering to negotiate resource representations   -->   <bean class= "Org.springframework.web.servlet.view.cOntentnegotiatingviewresolver ">  <!-- restful  whether to use the extension to determine the content format,id.json  return JSON format  -->    <property name= "Favorpathextension"  value= "true" ></ property>      <!-- restful  Whether parameter support is used to determine content format,id?format=json  Returns the JSON format  -->    <property name= "Favorparameter"  value= "true" ></ property>      <!-- restful  Ignore accept header,accept: Application/json -->    <property name= "IgnoreAcceptHeader"  value= " False ></property>        <!--  parse   -in sequence based on view ->    <property name= "Order"  value= "1"  />         <!--  Get the corresponding  accept  -->< for the new  URL  with extension, parameter Property name= "MediatypEs ">    <map>    <entry key=" JSON " value=" Application/json "/>        <entry key=" xml " value=" Application/xml "/>        <entry key=" html " value=" Text/html "/>    </map></property><!--  if extension, parameters even header  Information is not found for the corresponding accept when   --><property name= "Defaultcontenttype"  value= "text/html"/>< !--  render with the corresponding view   --><property name= "Defaultviews" >    < list ><!--  Convert Java objects to XML format Data  --><bean class= " Org.springframework.web.servlet.view.xml.MarshallingView "><constructor-arg ref=" Jaxbmarshaller "  /></bean><!--  Convert Java objects to json  format Data  --><bean class= " Org.springframework.web.servlet.view.json.MappingJacksonJsonView "/>     </list></property><!--  render   --><property name= with corresponding views " Viewresolvers ">    <list >    <!--  Find the bean with the ID defined in the context and locate the Id  -->        <bean class = "Org.springframework.web.servlet.view.BeanNameViewResolver"/>         <!--  Resolves the instance of the view returned in the controller, and the assembly URL navigates to the corresponding resource   -->         <bean id= "Viewresolver"  class= " Org.springframework.web.servlet.view.UrlBasedViewResolver "><property name=" Viewclass " value=" Org.springframework.web.servlet.view.JstlView "/><property name=" prefix " value="/web-inf/jsp/"/ ><property name= "suffix"  value= ". JSP"/></bean>    </list> </property></bean>

However, if the conversion mechanism is used:

<!--  Output string contents, non-path  --><bean id= "Stringconverter" class= " Org.springframework.http.converter.StringHttpMessageConverter "><property name=" Supportedmediatypes " ><list><value>text/plain;charset=UTF-8</value></list></property></bean> <!-- json --><bean id= "Jsonconverter" class= " Org.springframework.http.converter.json.MappingJacksonHttpMessageConverter "></bean> <bean  id= "Marshallinghttpmessageconverter"           class= " Org.springframework.http.converter.xml.MarshallingHttpMessageConverter ">         <constructor-arg ref= "Jaxbmarshaller"/>         <property name= "Supportedmediatypes"  value= "Application/xml"  />     </bean>    <!--  Content negotiation based on converters  -->    <bean id= "Jaxbmarshaller"  class= "Org.springframework.oxm.jaxb.Jaxb2Marshaller" >         <!-- xml Converters need to bind classes that need to be converted  -->         <property name= "Classestobebound" >             <list>                 <value>com.hnust.bean.Resource</value>             </list>         </property>    </bean>    <!--  Registered Object Converter    -->    <beanclass= " Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter ">    < Property name= "Messageconverters" ><list><ref bean= "Stringconverter" /><ref bean= "Jsonconverter"  />                         <ref bean= " Marshallinghttpmessageconverter "/></list></property>    </bean>

4 pom file, get jar Package

  <dependency><groupid>org.springframework</groupid><artifactid>spring-web </artifactId><version>3.2.8.RELEASE</version></dependency>    < Dependency><groupid>org.springframework</groupid><artifactid>spring-webmvc</artifactid ><version>3.2.8.RELEASE</version></dependency><dependency><groupId> Org.springframework</groupid><artifactid>spring-oxm</artifactid><version>3.2.8.release </version></dependency>   <dependency><groupid>javax.servlet</ groupid><artifactid>jstl</artifactid><version>1.2</version></dependency>< Dependency><groupid>log4j</groupid><artifactid>log4j</artifactid><version> 1.2.17</version></dependency><dependency><groupid>commons-logging</groupid>< artifactid>commons-logging</artifactid><version>1.1.3</version></dependency><dependency><groupid> Net.sf.json-lib</groupid><artifactid>json-lib</artifactid><version>2.4</version> <classifier>jdk15</classifier></dependency><dependency><groupId> Org.codehaus.jackson</groupid><artifactid>jackson-mapper-asl</artifactid><version> 1.9.13</version></dependency>    <dependency><groupid> javax.servlet</groupid><artifactid>servlet-api</artifactid><version>3.0-alpha-1</ Version></dependency>

5 Project Source Link:

http://download.csdn.net/detail/wp562846864/8113077

Description: There is no jar in the source code, because MAVEN project, jar package through the Pom file to fetch it, if really need, can leave a message .....












Spring MVC Rest Learning II

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.