[Spring MVC] Spring Mvc Foundation - Common Annotations, Conversions between Objects and json or xml

Keywords: JSON xml Spring IntelliJ IDEA

Reprinted from: http://blog.csdn.net/qq_26525215

Common Annotations for Spring MVC

@Controller

The @Controller annotation on the class indicates that the class is spring Controller in MVC declares it as a Spring Bean, and Dispatcher Servlet automatically scans the class annotated with this annotation and maps the Web request to the method annotated with @RequestMapping.

When declaring a normal Bean, the use of @Component, @Service, @Repository and @Controller is equivalent, because @Service, @Repository, @Controller all combine the @Component annotation.  
But when Spring MVC declares controller beans, it can only use @Controller.

@RequestMapping

The @RequestMapping annotation is used to map Web requests (access paths and parameters), place classes and methods.  
RequestMapping can be annotated on classes or methods. The @RequestMapping path of the annotation in the method inherits the path of the annotation on the class, and @RequestMapping supports the request and response of the Servlet as parameters, as well as configuring the media types of request and response.

@ResponseBody

ResponseBody supports putting the return value inside the response body rather than returning a page.  
In many Ajax-based programs, we can use this annotation to return data rather than pages, which can be placed before the return value or method.

@RequestBody

RequestBody allows request parameters to be in the request body, rather than behind the address directly linked to. This comment is set before the parameter.

RequBody can bind JSON strings in the body of the request to the corresponding bean s, or, of course, to the corresponding strings, respectively.

For example, in the following cases:

 $.ajax({
        url:"/login",
        type:"POST",
        data:'{"userName":"admin","pwd","admin123"}',
        content-type:"application/json charset=utf-8",
        success:function(data){
          alert("request success ! ");
        }
    });


    @requestMapping("/login")
    public void login(@requestBody String userName,@requestBody String pwd){
      System.out.println(userName+" : "+pwd);
    }

In this case, the values of two variables in the JSON string are assigned to two strings, but if I have a User class, I have the following fields:
      String userName; 
      String pwd; 
The above parameters can then be changed to the following form: @requestBody User user, which assigns the values in the JSON string to the corresponding attributes in user.
It is important to note that the key in the JSON string must correspond to the attribute name in the user, otherwise it can not be requested.

@PathVariable

PathVariable is used to receive path parameters, such as / new/001, and can receive 001 as a parameter. This annotation is set before the parameter.

For example:

@RequestMapping(value = "/new/{str}",produces = "text/plain;charset=UTF-8")
//The @ResponseBody method is also available
public @ResponseBody String demoPathVar(@PathVariable String str){
    return str;
}


@RestController

RestController is a composite annotation that combines @Controller and @ResponseBody, which means that you need to use this annotation when you only develop a control that interacts with data on a page.  
Without this annotation, you need to add @Controller and @ResponseBody annotations to your code to achieve the above functions.

Example

The following example demonstrates the use of these annotations.  
And using jackson to get the transformation between the object and json or xml!

 <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
            <version>2.8.5</version>
        </dependency>


In practical projects, we mainly support json data, and there is no need to support both json and xml, because json is more concise than xml.  
Because JavaScript With widespread use, json is the most recommended format. In this case, our dependency packages are as follows (the dependency packages above contain the following dependency packages):

 <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.5</version>
        </dependency>

package cn.hncu.model;

/**
 * Created with IntelliJ IDEA.
 * User: Chen Haoxiang.
 * Date: 2017/2/20.
 * Time: 8:59. PM
 * Explain:This class is used to demonstrate getting request object parameters and returning this object to response
 */
public class DemoObj {
    private Long id;
    private String name;

    public DemoObj() {
    }

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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


Note: When jackson converts objects to json, it must be empty!!!

Annotation Demonstration Controller

Demo code

package cn.hncu;

import cn.hncu.model.DemoObj;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * Created with IntelliJ IDEA.
 * User: Chen Haoxiang.
 * Date: 2017/2/20.
 * Time: 9:02. PM
 * Explain:Controller
 */
@Controller //Declare that this class is a controller
@RequestMapping("/chx") //The access path mapping this class is / chx
public class DemoAnnoController {
    private static Logger logger = LoggerFactory.getLogger(DemoAnnoController.class);

    @RequestMapping(produces = "text/plain;charset=UTF-8")
    //This method does not label paths, so class level paths / chx are used.
    // Produces can customize the media type and character set of the response returned, or if the return value is a json object, set produces = text / plain; charset = UTF-8
    public @ResponseBody String index(HttpServletRequest request){
        //The demonstration can accept HttpServletRequest as a parameter, or HttpServletResponse as a parameter, where @ResponseBody is used before the return value.
        logger.info("Get into index Method! The access path is:"+request.getRequestURI());
        return "url:"+request.getRequestURI()+" can access";
    }

    //Demonstrate accepting path parameters and using @PathVariable before method parameters!
    @RequestMapping(value = "/pathvar/{str}",produces = "text/plain;charset=UTF-8")
    public @ResponseBody String demoPathVar(@PathVariable String str,HttpServletRequest request){
        logger.info("Get into demoPathVar Method! The access path is:"+request.getRequestURI());
        return "url:"+request.getRequestURI()+" can access";
    }

    //Demonstrate the normal request parameter acquisition, access path is / chx/requestParam?id=001
    @RequestMapping(value = "/requestParam",produces = "text/plain;charset=UTF-8")
    public @ResponseBody String passRequestParam(Long id,HttpServletRequest request){
        logger.info("Get into passRequestParam Method! The access path is:"+request.getRequestURI());
        return "url:"+request.getRequestURI()+" can access,id:"+id;
    }

    //Demonstrate explanatory parameters to the object, access path is / CHX / obj /? Id = 001 & name = CHX
    @RequestMapping(value = "obj",produces = "application/json;charset=UTF-8")
    @ResponseBody //It can also be put on the method.
    public String passObj(DemoObj obj,HttpServletRequest request){
        logger.info("Get into passObj Method! The access path is:"+request.getRequestURI());
        return "url:"+request.getRequestURI()+" can access,obj id:"+obj.getId()+" obj name:"+obj.getName();
    }

    //Demonstrates mapping different paths to the same method.
    //Access path is / chx/name1 or / cha/name2
    @RequestMapping(value = {"/name1","name2"},produces = "text/plain;charset=UTF-8")
    public @ResponseBody String remove(HttpServletRequest request){
        logger.info("Get into remove Method! The access path is:"+request.getRequestURI());
        return "url:"+request.getRequestURI()+" can access";
    }

}

Demonstration results

RestController Demo

Code

package cn.hncu;

import cn.hncu.model.DemoObj;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA.
 * User: Chen Haoxiang.
 * Date: 2017/2/20.
 * Time: 10:10 p.m.
 * Explain: @RestController Demonstration
 */
@RestController //Declarations are controllers and @ResponseBody is not required when data is returned
@RequestMapping("rest")
public class DemoRestController {
    private static Logger logger = LoggerFactory.getLogger(DemoAnnoController.class);

    @RequestMapping(value = "getjson",produces = "application/json;charset=UTF-8")//The media type that returns data is json
    public DemoObj getjson(DemoObj obj){
        logger.info("Get into getjson Method.");
        return new DemoObj(obj.getId()+1,obj.getName()+" json");//Return the object directly, and the object is automatically converted to json
    }

    @RequestMapping(value = "getxml",produces = "application/xml;charset=UTF-8")//The media type that returns data is xml
    public DemoObj getxml(DemoObj obj){
        logger.info("Get into getxml Method.");
        return new DemoObj(obj.getId()+1,obj.getName()+" xml");//Return the object directly, and the object will automatically be converted to xml
    }

}

Demonstration results

Convert to json's result:

The results converted into xml:


Source links involved in this blog:

[- > Click on Access Source - CHX]

Posted by wtfsmd on Tue, 18 Dec 2018 00:12:04 -0800