Spring MVC develops RESTful interface

Concept:

What is REST?

REST is an abbreviation for representative state transfer. restful is an interface design style. It is not a protocol, usually based on HTTP protocol;

Why do you need such a style?

One of the key points of RESTful is uniform interface naming rules;

Each developer may have different interface styles, the most common ones are similar to getUserInfo,deleteUserInfo, etc.. But this is purely related to the habits of each developer, and problems may occur when multiple developers work together. Especially when the front and back offices are separated, the front office staff have to fill in a large number of different URLs to request data;

RESTful style:

rest regards every URI as a resource, which is a concept. In fact, it can be a picture, a record, and a group of records. Each request method corresponds to the operation on a resource, which usually includes the following four types:

  • GET get GET resources
  • PUT update resources
  • POST submission resources
  • DELETE delete resource

If we regard the user data with id 1 as a resource, we need to send a request address to the server to locate the resource when we operate the resource in the foreground, such as: http://localhost:8080/SSMDemo/user/1. After finding the resource through URI, we also need to tell the server what kind of operation we want to perform on the resource through HTTP request method, such as GET

Simply put: RESTful is to locate resources with URI s, and define operations to be performed through request methods;

At present, there are not many websites designed completely according to RESTful. Amazon is one of the earliest websites adopting this style. Its URL is like this: https://www.amazon.cn/gp/product/B00MCW8R1S

RESTful statelessness:

Stateless constraints make the change of the server invisible to the client. In two consecutive requests, the client does not depend on the same server, which makes the server have better scalability;

Benefits of RESTful for the system:

Reduce the complexity of development, improve the scalability of the system, and make the interface more standardized;

URI and URL:

URL is the uniform resource identifier (as long as a resource can be uniquely identified, it is called URI)

URL is the unified resource path

URL belongs to a kind of URI

RESTful in spring MVC

It can be seen that the change of RESTful lies in the processing of request address and the definition of request method;

We have two things to do:

  • You need to get some parameters from the URL
  • Different request methods of the same interface can complete corresponding operations

Case: design a RESTful interface to operate curriculum resources

Write controller

package com.kkb.controller;

import com.kkb.pojo.Course;
import com.kkb.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class RESTCourseController {

    @Autowired
    CourseService service;

    //Get all courses
        @RequestMapping(value = "/course",method = RequestMethod.GET)
    public List<Course> getCourseList(){
        System.out.println("getCourseList");
        return service.selectCourses();
    }  
    //Get a course based on id
    @RequestMapping(value = "/course/{id}",method = RequestMethod.GET)
    public Course getCourse(@PathVariable Integer id){
        System.out.println("getCourse");
        System.out.println("parameter:"+id);
        return service.selectByID(id);
    }
      //Add a new course
    @RequestMapping(value = "/course",method = RequestMethod.POST)
    public String addCourse(@RequestBody Course course){
        System.out.println("addCourse");
        System.out.println("parameter:"+course);
        service.insertCourse(course);
        return "{\"msg\":\"success\"}";
    }
        //Delete course according to id
    @RequestMapping(value = "/course/{id}",method = RequestMethod.DELETE)
    public String deleteCourse(@PathVariable Integer id){
        System.out.println("deleteCourse");
        System.out.println("parameter:"+id);
        service.deleteCourse(id);
        return "{\"msg\":\"success\"}";
    }
    //Update course based on id
    @RequestMapping(value = "/course",method = RequestMethod.PUT)
    public String updateCourse(@RequestBody Course course){
        System.out.println("updateCourse");
        System.out.println("parameter:"+course);
        service.updateCourse(course);
        return "{\"msg\":\"success\"}";
    }
}

@PathVariable is specially used to get parameters from url. Add {parameter name} in RequestMapping as a placeholder. The parameter name needs to be the same as the parameter name in the method. If it is different, add value for @ PathVariable (usually not necessary), as follows:

  @RequestMapping(value = "/course/{cid}",method = RequestMethod.GET)
    public Course getCourse(@PathVariable("cid") Integer id){
        System.out.println("getCourse");
        System.out.println("parameter:"+id);
        return service.selectByID(id);
    }

For interface test, it is recommended to use postman mac to use paw,

In addition, in the actual development, we need to pass the user token in the foreground to verify the identity, which can be realized by interceptors;

Supplement:

Tomcat only parses the parameters in get and post. If PUT or DELETE is used in spring MVC and form submission is used, the parameters cannot be obtained. Tomcat should be PUT into the request without parameters. Spring MVC provides a filter to help Tomcat parse the parameters in put/delete and PUT them into the request. The configuration method is as follows:

web.xml:

<!--To configure SpringMVC´╝îanalysis PUT/DELETE Form data in request-->
    <filter>
        <filter-name>HttpPutFormContentFilter</filter-name>
        <filter-class>org.springframework.web.filter.FormContentFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HttpPutFormContentFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

The above problems will not appear when using json interaction, because spring MVC obtains json data directly from the request body, not through request;

Verbose: if the form on the page uses PUT / or DELETE request mode, you need to add the above filter in web.xml;

Tags: Java Spring REST Tomcat xml

Posted on Thu, 13 Feb 2020 03:52:06 -0800 by kitaeshi