Java learning record 08spring MVC restful style

Spring MVC rest style

REST (Representational State Transfer) is the most popular software architecture style at present

REST refers to a set of architectural constraints and principles. Applications or designs that meet these constraints and principles are RESTful

REST features:

Resources: all things on the Internet can be abstracted as resources. It can be a text, a picture, a song, a service, in short, it is a concrete existence. A URI (uniform resource locator) can be used to point to it, and each resource corresponds to the URI of a feature. To obtain this resource, you can access its URI, so the URI is the unique identifier of each resource
PS: URI, uniform resource identifier, which represents every available resource on the web

Presentation layer: the form in which resources are concretely presented, which is called its presentation layer. For example, text can be expressed in txt format, HTML format, XML format, JSON format, or even binary format

State transfer: each request represents an interactive process between the client and the server. HTTP protocol is a stateless protocol, that is, all States are saved on the server side. Therefore, if the client wants to operate the server, it must use some means to make the server "state transfer". This transformation is based on the presentation layer, so it is "presentation layer state transformation"

REST URL request form

When using a URL to represent a resource, each resource is represented by a unique URL, and the HTTP method is used to represent the operation, that is, accurately describe the server's processing actions (GET, POST, PUT, DELETE) on the resource to realize the addition, deletion, modification and query of the resource

Request typeexplain
GETGet resources
PSOTCreate resource
PUTUpdate resources
DELETEDelete resource

The difference between traditional URLs and REST style URLs

Traditional URLREST style URLResource operation mode
http://localhost:8080/getUser.do?id=12GET: http://localhost:8080/user/12Get user information
http://localhost:8080/saveUser.doPOST: http://localhost:8080/userNew user information
http://localhost:8080/updateUser.do?=12PUT: http://localhost:8080/user/12Update user information
http://localhost:8080/deleteUser.do?=12DELETE: http://localhost:8080/user/12Delete user information

REST application

Application premise:

  • Add filter org springframework. web. filter. Hiddenhttpmethodfilter specifies the request or all requests

web.xml configuration filter HiddenHttpMethodFilter

<!-- HiddenHttpMethodFilter The filter can POST Request converted to put Request and delete request! -->
<filter>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

rest.jsp page

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<script src="/js/jquery-1.11.1.js"></script>
<html>
<head>
    <title>REST style</title>
</head>
<body>
    <h1>REST style URL test</h1>
    
    <h2>General request test</h2>
    
    <h3>get request</h3>
    <a href="/rest/12">Get</a>

    <h3>post request</h3>
    <form action="/rest/12" method="post">
        <input type="submit" value="POST"/>
    </form>
    
    <h3>put request</h3>
    <form action="/rest/12" method="post">
        <input type="hidden" name="_method" value="PUT" />
        <input type="submit" value="PUT" />
    </form>
    
    <h3>delete request</h3>
    <input type="hidden" name="_method" value="DELETE"/>
    <form action="/rest/12" method="post">
        <input type="hidden" name="_method" value="DELETE" />
        <input type="submit" value="DELETE" />
    </form>
    
    <h2>AJAX Request test</h2>
    <form action="" id="myForm" method="post">
        id: <input type="text" id="id"> <br>
        name: <input type="text" id="name"> <br>
        age: <input type="text" id="age"> <br>
        <button type="button" id="getAjax">GET</button> <br>
        <button type="button" id="postAjax">POST</button>   <br>
        <button type="button" id="putAjax">PUT</button> <br>
        <button type="button" id="deleteAjax">DELETE</button>   <br>
    </form>

    <script>
        $(function(){
            // get
            $("#getAjax").click(function(){
                $.ajax({
                    type: "GET",
                    url: "/rest/"+$("#id").val(),
                    data:"name="+$("#name").val()+"&age="+$("#age").val(),
                    dataType:"json",
                    success: function(){}
                });
            });
            
            // post
            $("#postAjax").click(function(){
                $.ajax({
                    type: "POST",
                    url: "/rest/"+$("#id").val(),
                    data:{
                        "name":$("#name").val(),
                        "age":$("#age").val() },
                    dataType:"json",
                    success: function(){}
                });
            });
            
            // put
            $("#putAjax").click(function(){
                $.ajax({
                    type: "POST",
                    url: "/rest/"+$("#id").val(),
                    data:{
                        "_method":"PUT",
                        "name":$("#name").val(),
                        "age":$("#age").val() },
                    dataType:"json",
                    success: function(){}
                });
            });
            
            //delect
            $("#deleteAjax").click(function(){
                $.ajax({
                    type: "POST",
                    url: "/rest/"+$("#id").val(),
                    data:{
                        "_method":"DELETE",
                        "name":$("#name").val(),
                        "age":$("#age").val() },
                    dataType:"json",
                    success: function(){}
                });
            });
        });
    </script>
</body>
</html>

RestController class controller

package com.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("rest")
public class RestController {
    
    @RequestMapping("torest")
    public String torest() {
        return "jsp/rEST";
    }
    
    @RequestMapping(value = "{id}",method = RequestMethod.GET)
    public String getTest(String name ,Integer age) {
        System.out.println("get request");
        System.out.println("name : " + name);
        System.out.println("age : " + age);
        return "jsp/ok";
    }
    
    @RequestMapping(value = "{id}",method = RequestMethod.POST)
    public String postTest(String name ,Integer age) {
        System.out.println("post request");
        System.out.println("name : " + name);
        System.out.println("age : " + age);
        return "jsp/ok";
    }
    
    @RequestMapping(value = "{id}",method = RequestMethod.PUT)
    public String putTest(String name ,Integer age) {
        System.out.println("put request");
        System.out.println("name : " + name);
        System.out.println("age : " + age);
        return "jsp/ok";
    }
    
    @RequestMapping(value = "{id}",method = RequestMethod.DELETE)
    public String deleteTest(String name ,Integer age) {
        System.out.println("delete request");
        System.out.println("name : " + name);
        System.out.println("age : " + age);
        return "jsp/ok";
    }
    
}

Click test response by entering the page!!!

REST URL problem

Avoid multi-level URL s

If resources have multi-level classification, it is not recommended to write multi-level URL s, such as:

GET: / class/12/student/1002 suggestion = > GET: / class/12?student=1002 (check the designated students in the class)

Parameter transmission problem

The parameters passed in Restful PUT and DELETE requests are invalid, and the parameter value passed to the background is null

Tomcat encapsulation request description:

  • Encapsulate the data in the request into a map
  • request.getParameter(Key) will get the value in the map
  • Spring MVC encapsulates POJO objects, but POJO will pass request Getparameter (key) is used to obtain, so UPT and DELETE request Getparameter (key) will not be available
  • Tomcat detects that PUT and DELETE will not encapsulate the requested data map

Solution

Add with POST request_ The method attribute value is the specified request type (PUT, DELETE,...), provided that a filter is required

  1. web.xml configuration filter HiddenHttpMethodFilter

    <!-- HiddenHttpMethodFilter The filter can POST Request converted to put Request and delete request! -->
    <filter>
        <filter-name>hiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>hiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
  2. Page request

    ···
    <!--form Form request
    	Add hidden attribute _method
    	The request type is: PUT
    -->
    <form action="/rest/12" method="post">
        <input type="hidden" name="_method" value="PUT" />
        <input type="submit" value="PUT" />
    </form>
    ···
    <!--ajax request
    	Add attribute _method
    	The request type is: DELETE
    -->
    <button id="deleteAjax">DELETE request</button>
    ···
    <script>
        $(function(){
            //delect
            $("#deleteAjax").click(function(){
                $.ajax({
                    type: "POST",
                    url: "/rest/12",
                    data:{"_method":"DELETE"},
                    dataType:"json",
                    success: function(){}
                });
            });
        });
    </script>
    

Keywords: Java Web Development Ajax

Added by jbachris on Sat, 15 Jan 2022 23:07:00 +0200