springMVC note series (7) - HiddenHttpMethodFilter filter

What is REST? Let's start with an introduction.
REST: Representational State Transfer. (Resource) Presentation layer state transition. It is one of the most popular Internet software architectures. It has a clear structure, conforms to standards, is easy to understand, and is easy to expand, so it is being adopted by more and more websites.

Resources (Resources) : An entity on the network, or a specific information on the network. It can be a piece of text, a picture, a song, a service, in short, a concrete existence. It can be pointed to with a URI (Uniform Resource Locator), each resource corresponding to a specific URI. To get this resource, just visit its URI, so URI is a unique identifier for each resource.

Representation layer (Representation) : The form in which the resource is concretely presented is called its Representation layer (Representation). For example, text can be represented in txt format, HTML format, XML format, JSON format, or even binary format.

State Transfer : Each time a request is issued, it represents an interaction between the client and the server. The HTTP protocol is a stateless protocol, that is, all states are stored on the server side. Therefore, if the client wants to operate the server, there must be some means to make the server-side happen"
State transfer" (State Transfer). And this conversion is built on the presentation layer, so it is the "presentation layer state transfer". Specifically, it is the four verbs that express the operation mode in the HTTP protocol: GET, POST, PUT and DELETE. They correspond to four basic operations: GET is used to obtain resources, POST is used to create new resources, PUT is used to update resources, and DELETE is used to delete resources. (This article comes from: http://my.oschina.net/ happyBKs/blog/416994)
Examples:
- /order/1 HTTP GET : get order with id = 1
- /order/1 HTTP DELETE: delete order with id = 1
- /order/1 HTTP PUT: update order with id = 1
– /order HTTP POST: Add order
but use spring to implement four methods requires a filter:

HiddenHttpMethodFilter: The browser form only supports GET and POST requests, but DELETE, PUT and other methods are not supported. Spring3.0 added A filter that converts these requests to standard http methods, enabling support for GET, POST, PUT and DELETE requests.
URLs with placeholders are a new addition to Spring 3.0, which moves towards REST goals in SpringMVC milestones in the process.
The placeholder parameter in the URL can be bound to the input parameter of the controller processing method through @PathVariable: The {xxx} placeholder in the URL can be bound to the input parameter of the operation method through @PathVariable("xxx") .

Well, not much to say, let's practice it, add the HiddenHttpMethodFilter filter to the original web.xml in the webapp directory

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!-- Configure org.springframework.web.filter.HiddenHttpMethodFilter, you can convert POST request to PUT or 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>
<!-- 配置DispatcherServlet -->
<!-- The following code is automatically generated for STS, if it is a general eclipse, you need to install the springIDE plug-in -->
<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- Configure an initialization parameter of DispatcherServlet: configure springmvc configuration location and name-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value><!-- classpath下的springmvc.xml -->
</init-param>
<!-- load-on-startup means that the servlet is created when the current web application is loaded, not when it is first requested -->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling
/ means that all requests can be answered and handled by springDispatcherServlet -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>


Compared with the examples in the previous articles, springMVC.xml has not changed. It is also given here for the convenience of readers. For the project structure and configuration of springMVC, please refer to my previous articles.


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<!-- Configure auto-scanned packages-->
<context:component-scan base-package="com.happyBKs.springmvc.handlers"></context:component-scan>
<!-- Configure the view parser: how to parse the return value of the handler method into the actual physical view -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>


Next, write the controller class and its methods to be responsible for receiving and processing requests: RestTestHandler class

package com.happyBKs.springmvc.handlers;
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.RequestMethod;
@RequestMapping("/rest")
@Controller
public class RestTestHandler {
/*
* Rest style Url originally used the style of request parameters
* Take CRUD as an example
* New: /order POST
* 修改:/order/1 Put update?id=1
* Get: /order/1 GET get?id=1
* Delete: /order/1 DELETE delete?id=1
*
* How to send PUT request and DELETE request?
* 1. Need to configure HiddenHttpMethodFilter
* 2. Need to send a POST request
* 3. Need to carry a hidden field with name=”_method” when sending POST request, the value is DELETE or PUT
*
* How to get the id in the SpringMVC target method?
* Annotate with @PathVariable
*/
@RequestMapping(value="/methodstest/{id}",method=RequestMethod.GET)
public String restGet(@PathVariable int id)//When @PathVariable is not marked with {id},
{
System.out.println("get "+id);
System.out.println("querry operations...");
return "querry";
}
@RequestMapping(value="/methodstest",method=RequestMethod.POST)
public String restPost()
{
System.out.println("post ");
System.out.println("post operations...");
return "post";
}
@RequestMapping(value="/methodstest/{id}",method=RequestMethod.PUT)
public String restPut (athPathVariable int id)
{
System.out.println("put "+id);
System.out.println("put operations...");
return "put";
}
@RequestMapping(value="/methodstest/{id}",method=RequestMethod.DELETE)
public String restDelete (athPathVariable int id)
{
System.out.println("delete "+id);
System.out.println("delete operations...");
return "delete";
}
}


The request page is written as follows:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="rest/methodstest/1">GET Request</a>
<form action="rest/methodstest" method="post">
<input type="submit" value="POST Request" />
</form>
<form action="rest/methodstest/1" method="post">
<input type="hidden" name="_method" value="PUT">
<input type="submit" value="PUT Request" />
</form>
<form action="rest/methodstest/1" method="post">
<input type="hidden" name="_method" value="DELETE">
<input type="submit" value="DELETE Request" />
</form>
</body>
</html>


Did you notice? HiddenHttpMethodFilter helps us simulate put and delete requests. It will convert POST request with hidden field _method into put request and delete request to submit to the server.
Process:



Click on four links and form buttons:








Console input is:

get 1
querry operations...
post
post operations...
put 1
put operations...
delete 1
delete operations..


Summary:
Rest-style Url originally used the style of request parameters
* Take CRUD as an example
* Add: /order POST
* Modify: /order/1 Put update?id=1
* Get: /order/1 GET get?id=1
* Delete: /order/1 DELETEdelete?id=1

* How to send PUT request and DELETE request?
1. Need to configure HiddenHttpMethodFilter
2. Need to send POST request
3. Need to carry a hidden field with name=”_method” when sending POST request, the value is DELETE or PUT
* How to get the id in the target method of SpringMVC?
Use

@PathVariable : http://bbs.it-home.org/thread-45619-1-1.html

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326779553&siteId=291194637