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
两种请求, 所以需要在表单中配置隐藏域
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>