Loading

如何在SSM中使用Restful风格

1. 编写User实体类

package com.itheima.po;
/**
 * 用户POJO
 */
public class User {
	private Integer id;
	private String username;
	private String password;

	// 省略get、set、 toString方法	
}

2. 编写Controller类

package com.itheima.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.itheima.po.User;

@Controller
@RequestMapping("/user")
public class UserRestfulController {
	
	@GetMapping("/*")
	public String get() {
		System.out.println("get请求");
		return "success";
	}
	
	@PostMapping("/{user}")
	public String post(User user) {
		System.out.println("post请求");
		System.out.println(user);
		return "success";
	}
	
	@PutMapping("/{user}")
	public String put(User user) {
		System.out.println("PUT请求");
		System.out.println(user);
		return "redirect:user";
	}

	@DeleteMapping("/{id}")
	public String delete(String id) {
		System.out.println("DELETE请求");
		System.out.println("删除id:" + id);
		return "redirect:user";
	}

}

post, get 请求方法中设置重定向页面,否则会出现浏览器 405 错误

3. 编写测试页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>RESTful测试</title>
	
</head>
<body>
	<h2>POST请求</h2>
	<form action="${pageContext.request.contextPath}/user/user" method="post">		
		id:<input type="text" name="id"/><br>
		用户名:<input type="text" name="username"/><br>
		密码:<input type="password" name="password"/><br>
		<input type="submit" value="提交"/>
	</form>
	
	
	
	<h2>PUT请求</h2>
	<form action="${pageContext.request.contextPath}/user/user" method="post">
		<input type="hidden" name="_method" value="put">		
		id:<input type="text" name="id"/><br>
		用户名:<input type="text" name="username"/><br>
		密码:<input type="password" name="password"/><br>
		<input type="submit" value="提交"/>
	</form>
	
	<h2>DELETE请求</h2>
	<form action="${pageContext.request.contextPath}/user/id" method="post">
	<input type="hidden" name="_method" value="delete">
		id:<input type="text" name="id"/><br>
		<input type="submit" value="提交"/>
	</form>
	

</body>
</html>

因为表单只支持 post, get 两种请求, 所以需要在表单中配置隐藏域

input 表单的隐藏域 name 必须是 _method, value 是对应请求的属性,例如 putdelete

4. 配置 HiddenHttpMethodFilter 过滤器

在web.xml配置文件中配置


   	<!-- 配置过滤器 将POST请求转换为PUT和DELETE请求 -->
	<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>

posted @ 2020-12-14 16:52  hanlin-hl  阅读(344)  评论(0编辑  收藏  举报