Restful風格 牛刀小試

本文重點:web項目融合Restful風格

百度百科 瞭解一下Restful

RESTful   

一種軟件架構風格、設計風格,而不是標準,只是提供了一組設計原則和約束條件。它主要用於客戶端和服務器交互類的軟件。基於這個風格設計的軟件可以更簡潔,更有層次,更易於實現緩存等機制。

 

Restful風格的web項目最直觀的兩點

♦ url的規範

非REST風格的URL:http://localhost:8080/user?id=1&type=1

REST風格的URL:http://localhost:8080/user/1/1

對比起來,不難感覺REST風格的URL自帶牛逼屬性,看起來就是舒服

♦ 用HTTP的4個動詞標識對資源的操作類型

GET:獲取

POST:新增

PUT:修改

DELETE:刪除

 

《========優雅分割=====進入主題========》

《========WEB如何實現REST風格========》

 

♦♦ Step One:配置spring支持Put/Delete請求

Spring默認是不支持Put/Delete請求的,那我們該如何配置呢?

打開web.xml,添加如下配置

<!-- 配置springmvc支持put/delete請求 -->
<filter>
	<filter-name>HttpMethodFilter</filter-name>
	<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
	<filter-name>HttpMethodFilter</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>

♦♦ Step Two:準備Pojo

public class User {
	private String name;
	private Integer age;
    //省略Get、Set
}

♦♦ Step Three:四種請求的Controller層代碼

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mote.pojo.User;
import com.mote.service.UserService;

@RequestMapping("/user")
@Controller
public class UserConroller {

	@Autowired
	private UserService userService;

	/**
	 * GET請求:獲取用戶
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/{id}")
	@ResponseBody
	public ResponseEntity<User> getUser(@PathVariable("id") int id) {

		User user = userService.getUser(id);

		return new ResponseEntity<User>(user, HttpStatus.OK);
	}

	/**
	 * POST請求:添加用戶
	 * @param user
	 * @return
	 */
	@PostMapping()
	@ResponseBody
	public ResponseEntity<Integer> addUser(@RequestBody User user) {

		Integer numb = userService.addUser(user);

		return new ResponseEntity<Integer>(numb, HttpStatus.OK);
	}
	
	/**
	 * PUT請求:修改用戶
	 * 
	 * @param user
	 * @return
	 */
	@PutMapping()
	@ResponseBody
	public ResponseEntity<Integer> updUser(@RequestBody User user) {
		
		Integer numb = userService.updUser(user);

		return new ResponseEntity<Integer>(numb, HttpStatus.OK);
	}
	
	/**
	 * DELETE請求: 刪除用戶
	 * 
	 * @param id
	 * @return
	 */
	@DeleteMapping("/{id}")
	@ResponseBody
	public ResponseEntity<Integer> delUser(@PathVariable("id") int id) {

		Integer numb = userService.delUser(id);

		return new ResponseEntity<Integer>(numb, HttpStatus.OK);
	}
}

♦♦Step Four:四種請求對應的Ajax請求

//獲取ID爲1的用戶
	function getUser() {
		$.ajax({
			url : "/restful/user/1",
			type : "get",
			success : function(data) {
				console.log(data);
			},
			error : function(data) {
				alert("服務器繁忙");
			}
		})
	}

	//添加用戶
	function addUser() {
		var params = {
			name : "MrsY",
			age : 23
		}
		$.ajax({
			url : "/restful/user",
			contentType : 'application/json',
			data : JSON.stringify(params),
			type : "post",
			success : function(data) {
				console.log(data);
			},
			error : function(data) {
				alert("服務器繁忙");
			}
		})
	}

	//更新用戶
	function updUser() {
		var params = {
			id : 1,
			name : "MrsY",
			age : 23
		}
		$.ajax({
			url : "/restful/user",
			contentType : 'application/json',
			data : JSON.stringify(params),
			type : "put",
			success : function(data) {
				console.log(data);
			},
			error : function(data) {
				alert("服務器繁忙");
			}
		})
	}

	//添加ID爲1的用戶
	function delUser() {
		$.ajax({
			url : "/restful/user/1",
			type : "delete",
			success : function(data) {
				console.log(data);
			},
			error : function(data) {
				alert("服務器繁忙");
			}
		})
	}

 

tip:實踐過程中最容易碰到Ajax請求進不去後臺方法,控制檯報各種40x錯誤,這時候注意參考上面的代碼,後臺注意Spring註解的使用,前端注意Ajax參數的配置。 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章