Java - Restful style

REST and a RESTful:
REST: presentation layer state transition, resource state transition in the network in some form.
RESTful REST is a style of development based on the concept, the development of specific rules.

 

 

 Server returns only data, or to json xml format.

 

RESTful development specifications:
  • Use a URL as user interaction entrance
  • explicit semantic specification (GET | POST | PUT | DELETE)
  • returns only the data (JSON | XML), contains no show

RESTful naming requirements:

 

 

 

1. The first RESTful application

@Controller 
@RequestMapping ( "/ RESTful")   // the URL is all nouns 
public  class RestfulController { 
    @GetMapping (value = "/ Request", Produces = "file application / JSON; charset = UTF-. 8" ) 
    @ResponseBody 
    public doGetRequest String () {
         return "{\" Message \ ": \" test \ "}";   // use \ output Yoshito 
    } 
}

 

2. To achieve RESTful laboratory

General PC and mobile terminal can call API interface, the following analog PC end calls, use Ajax:

 

 

 Send page via ajax request:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>RESTful</title>
    <script src="jquery-3.4.1.min.js"></script>
    <script>
        $(function () {
            $("#btnGet").click(function () {
                $.ajax({
                    url : "/restful/request",
                    type : "get",
                    dataType : "json",
                    success : function (json) {
                        $("#message").text(json.message)
                    }
                })
            })
        })
    </script>
</head>
<body>
<input type="button" id="btnGet" value="发送Get请求">
<h2 id="message"></h2>
</body>
</html>

Because the definition of the root directory of the webapp as static files, so client.html can be accessed directly.

 

 

 Actually produced a garbled view the request header found the use of incorrect character set.

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>test/html;charset=utf-8</value>
                    <!--通知浏览器以这种格式加载数据-->
                    <value>application/json;charset=utf-8</value>
                </list>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

Add the above configuration on it. (Ajax can only solve the garbage problem)

 

3.RestController Notes and path variables

(1)RestController

@Controller 
@RequestMapping ( "/ RESTful")   // the URL is all nouns 
public  class RestfulController { 
    @GetMapping (value = "/ Request", Produces = "file application / JSON; charset = UTF-. 8" ) 
    @ResponseBody 
    public doGetRequest String () {
         return "{\" Message \ ": \" test \ "}";   // use \ output Yoshito 
    } 
}

If we want to return the plain text data, we must use @ResponseBody this comment.
If we use @RestController this annotation, then the following methods are all class returns plain text data.

@RestController 
@RequestMapping ( "/ RESTful")   // the URL is all nouns 
public  class RestfulController { 
    @GetMapping (value = "/ Request", Produces = "file application / JSON; charset = UTF-. 8" )
     public String doGetRequest () {
         return "{\" Message \ ": \" test \ "}";   // use \ output Yoshito 
    } 
}

@RestController can help us simplify development.

(2) Path Variable

/ Request / 1 for variables in the URL we can call path variable. So how do you value it?

@RestController
@RequestMapping("/restful")  //URL中所有的都是名词
public class RestfulController {
    @GetMapping(value = "/request/{rid}",produces = "application/json;charset=utf-8")
    public String doGetRequest(@PathVariable("rid") Integer requestId){
        System.out.println(requestId);
        return "{\"message\":\"测试\"}";  //使用\原义输出
    }
}

Annotations using @PathVariable receive path variable, and then assigned to the parameter method.

 

4.JSON serialization

(1) the step of introducing

Introducing dependencies:

< Dependency > 
    < groupId > com.fasterxml.jackson.core </ groupId > 
    < artifactId > jackson-Core </ artifactId > 
    <-! Be sure to use later versions 2.9.9, or there will be security issues -> 
    < Version > 2.9.9 </ Version > 
</ dependency > 
<-! root causes jackson interact with the target object -> 
< dependency > 
    < groupId > com.fasterxml.jackson.core </ groupId > 
    <artifactId>jackson-databind</artifactId>
    <version>2.9.9</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.9.9</version>
</dependency>

 spring is smart, as long as the check jackson-core and jackson-databind these two dependencies.
Jackson is automatically enabled us to provide json serialization services.

Create entity classes:

public class Person {
    private String name;
    private String address;
}

Write controller:

@GetMapping ( "/ Person / PID {}" )
 public the Person findByPersonId (@PathVariable ( "PID" ) Integer the personId) { 
    the Person Person = new new the Person ();
     IF (the personId ==. 1 ) { 
        person.setName ( "Kobe" ); 
        person.setAddress ( "Luotian" ); 
    } the else  IF (the personId == 2 ) { 
        person.setName ( "Yeh" ); 
        person.setAddress ( "Hubei Anlu" ); 
    } the else { 
        person.setName ( "Anonymous" );
    }
    return person;
}

If we return to a solid object, and configure the @RestController or @ResponseBody, then jackson will automatically provide serialization services.

access:

 

 

 

(2) a plurality of objects Returns

If a return multiple objects, we can List collection:

@GetMapping("/persons")
public List<Person> findPersons(){
    List list = new ArrayList();
    Person p1 = new Person();
    p1.setName("科比");
    p1.setAddress("湖北罗田");
    Person p2 = new Person();
    p2.setName("科比");
    p2.setAddress("湖北罗田");
    list.add(p1);
    list.add(p2);
    return list;
}

 

 

In the front end, we will receive the following data:

 

 

 In the page, we can extract the following manner:

$(function () {
    $("#btnPersons").click(function () {
        $.ajax({
            url : "/restful/persons",
            type : "get",
            datatype : "json",
            success : function (json) {
                console.info(json)
                for(var i=0;i<json.length;i++){
                    var p = json[i];
                    $("#divPersons").append("<h2>" + p.name + "-" + p.address + "</h2>")
                }
            }
        })
    })
})

 

(3) Processing time

Note that, jackson not friendly to time to deal with:
Add an event attribute:
Private a Date Birthday;
if not treated, is the direct return in the form of stamp events.

 

 

 We only need to add the corresponding time annotations:
@JsonFormat (pattern = "the MM-dd-YYYY HH: mm: SS")
Private a Date Birthday;
normal output of:

 

 

 Note that there is time to use the default Green, specify the time zone:
@JsonFormat (pattern = "the MM-dd-YYYY HH: mm: SS", TimeZone = "GMT +. 8")
Private a Date Birthday;

 

5. The browser's same-origin policy

Origin policy: to prevent access to resources on another domain from a domain script loaded.
Two different domain websites can not be accessed by Ajax, this is due to security considerations.
For example, the following two addresses, although essentially a page, but it belongs to a different source.

As long as the protocol, domain name, port any different, are as different domains.
Browser Console see Access-Control-Allow-Origin represents a cross-domain.

HTML tags allowed cross-domain:
  <IMG> explicit remote image
  <script> Remote loading the JS
  <Link> Remote loading CSS

 

6.SpringMVC solve cross-domain

CORS is a mechanism to use additional HTTP header tells the browser to access other domains.
URL response header included in Access-Control- * allowed cross-domain request specified.

(1) @CrossOrigin - Controller across domains comment

@RestController
@RequestMapping("/restful") 
@CrossOrigin(origins = {"*"}) 
public class RestfulController {
    @GetMapping(value = "/request/{rid}",produces = "application/json;charset=utf-8")
    public String doGetRequest(@PathVariable("rid") Integer requestId){
        System.out.println(requestId);
        return "{\"message\":\"测试\"}"; 
    }
}

(2) <mvc: cors> Spring MVC Global cross-domain configuration

<MVC: CORS> 
    <- path which path to allow cross-domain access -!> 
    <- who is allowed allowed Origins-domain access -!> 
    <- - Age-set buffer time max!> 
    < MVC: Mapping path = "*" allowed-Origins = "*" /> 
</ MVC: CORS>

 

Guess you like

Origin www.cnblogs.com/yangmingxianshen/p/12521605.html