1. 程式人生 > >SpringMVC的學習(七)——RESTful風格

SpringMVC的學習(七)——RESTful風格

一、RESTful介紹

REST:即Representational State Transfer , (資源)表現層狀態轉化,是目前最流行的一種網際網路軟體架構。它結構清晰、符合標註、易於理解、方便擴充套件,所以越來越多的網站採用!

具體說,就是HTTP協議裡面,四個表示操作方式的動詞:

GET POST PUT DELETE

它們分別代表著四種基本操作:

- GET 用來獲取資源     查詢

- POST用來建立新資源  新增

- PUT用來更新資源     更新

- DELETE用來刪除資源  刪除

示例:

- /order/1     HTTP GET :得到id = 1 的 order

- /order/1     HTTP DELETE: 刪除 id=1 的order

- /order       HTTP  PUT : 更新id = 1的 order

- /order       HTTP POST : 新增 order
二、SpringMVC實現RESTful風格

HiddenHttpMethodFilter:瀏覽器form表單只支援GET和POST,不支援DELETE和PUT請求,Springmvc添加了一個過濾器,可以將這些請求轉換為標準的http方法,支援GET,POST,DELETE,PUT請求!

三、RESTful風格介面開發

①HiddenHttpMethodFilter配置

web.xml新增HiddenHttpMethodFilter配置

<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>

控制層實現增刪改查:

@Controller
@RequestMapping("/order")
public class OrderController {

	OrderDao orderDao = new OrderDao();

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Model model) {
		// 獲取使用者列表
		Collection<Order> all = orderDao.getAll();
		model.addAttribute("orderList", all);
		return "order/list";
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	public String delete(@PathVariable("id") Integer id) {
		// 執行刪除操作
		System.out.println("id = " + id);
		orderDao.delete(id);
		return "redirect:/order/list";
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public String getById(@PathVariable("id") Integer id, Model model) {
		Order order = orderDao.get(id);
		model.addAttribute("order", order);
		return "order/update";
	}

	@RequestMapping(method = RequestMethod.PUT)
	public String update(Order o) {
		// 執行更新操作
		Integer id = o.getId();
		System.out.println("id = " + id);
		orderDao.update(o);
		return "redirect:/order/list";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String save(Order order) {
		// 執行增加操作
		orderDao.save(order);
		return "redirect:/order/list";
	}

}

list.jsp頁面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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=UTF-8">
<title>使用者首頁</title>
</head>
<body>
	<h1>獲取使用者列表</h1>
	<table align="center" width="60%" border="1px" bordercolor="#FB5832"
		CELLSPACING="0">
		<tr>
			<td>id</td>
			<td>訂單</td>
			<td>金額</td>
			<td>操作</td>
		</tr>
		<c:forEach items="${orderList }" var="order">
			<tr>
				<td>${order.id}</td>
				<td>${order.code}</td>
				<td>${order.money}</td>
				<td>
				 <a href="javascript:void(0)"onclick="deleteById(${order.id})">刪除</a> 
				 <a href="${pageContext.request.contextPath}/order/${order.id}">更新</a>
				</td>
			</tr>
		</c:forEach>
		<a href="${pageContext.request.contextPath}/page/add">新增</a>
	</table>

	<form action="/order/1" method="post" id="deleteForm">
		<input type="hidden" name="_method" value="DELETE" />
	</form>

	<script>
         function deleteById(id) {
            //TODO 刪除
             var form = document.getElementById("deleteForm");
             form.action = "${pageContext.request.contextPath}/order/"+id;
             form.submit();
         }
     </script>

</body>
</html>

需要注意: 由於doFilterInternal方法只對method為post的表單進行過濾,所以在頁面中必須如下設定:

代表post請求,但是HiddenHttpMethodFilter將把本次請求轉化成標準的put請求方式! name="_method"固定寫法

add.jsp頁面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>新增訂單</title>
</head>
<body>
  <h3>新增訂單</h3>
        <form action="${pageContext.request.contextPath}/order" method="post">
               <label for="code">訂單<input id="code" type="text" name="code" /></label>
               <label for="money">總金額<input id="money" type="text" name="money" /></label>
               <button>新增訂單</button>
        </form>
</body>
</html>

update.jsp頁面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h3>更新訂單</h3>
	<form action="${pageContext.request.contextPath}/order" method="post">
	    <input type="hidden" name="_method" value="PUT" />
		<label for="code">ID <input id="code" type="text" name="id"
			value="${order.id}" /></label><br /> <label for="code">訂單 <input
			id="code" type="text" name="code" value="${order.code}" /></label><br /> <label
			for="money">總金額<input id="money" type="text" name="money"
			value="${order.money}" /></label><br />
		<button>更新訂單</button>
	</form>
</body>
</html>

實體層

public class Order {

	private Integer id;
	private String code;
	private Double money;

	public Order() {
	}

	public Order(Integer id, String code, Double money) {
		this.id = id;
		this.code = code;
		this.money = money;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public Double getMoney() {
		return money;
	}

	public void setMoney(Double money) {
		this.money = money;
	}

}

資料庫訪問層:

public class OrderDao {

	private static Map<Integer, Order> orders = null;

	// 虛擬資料
	static {
		orders = new HashMap<Integer, Order>();
		orders.put(1, new Order(1, "訂單1", 20.5));
		orders.put(2, new Order(2, "訂單2", 22.5));
		orders.put(3, new Order(3, "訂單3", 24.5));
		orders.put(4, new Order(4, "訂單4", 25.5));
		orders.put(5, new Order(5, "訂單5", 26.5));
	}

	public static Integer initId = 6; // 記錄id

	/**
	 * 儲存/更新 order
	 * 
	 * @param order
	 */
	public void save(Order order) {
		if (order.getId() == null) {
			order.setId(initId++);
		}
		orders.put(order.getId(), order);
	}

	/**
	 * 返回所有資料
	 * 
	 * @return
	 */
	public Collection<Order> getAll() {
		return orders.values();
	}

	/**
	 * 獲取資料
	 * 
	 * @param id
	 * @return
	 */
	public Order get(Integer id) {
		return orders.get(id);
	}

	/**
	 * 刪除
	 * 
	 * @param id
	 */
	public void delete(Integer id) {
		orders.remove(id);
	}

	/**
	 * 更新
	 */
	public int update(Order o) {
		Order order = orders.get(o.getId());
		order.setCode(o.getCode());
		order.setMoney(o.getMoney());
		return 1;
	}
}