Restful Web API應該嚴格遵守Http的四個操作:
1、GET對應查詢操作;
2、POST對應創建操作;
3、PUT對應更新操作;
4、DELETE對應刪除操作。
從HttpClient發過來的Request類型只能是上述四種之一。
下面是我做的一個例子,這樣可以更快的理解
import org.springframework.beans.factory.annotation.Autowired;
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;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.cf.pojo.User;
import com.cf.rest.service.RestService;
@Controller
public class RestController {
@Autowired
private RestService restService;
/**
* 查詢操作 REST風格 : /user/用戶id
*
*/
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
@ResponseBody
public String get(@PathVariable("id") Long id) {
User user = restService.selectByPrimaryKey(id);
String result = JSON.toJSONString(user);
System.out.println("---------------------------get:" + result);
return result;
}
/**
* 創建操作 REST風格
*
*/
@RequestMapping(value = "/user/register", method = RequestMethod.POST)
@ResponseBody
public String register(User user) {
String result = JSON.toJSONString(user);
System.out.println("---------------------------Post:" + result);
return result;
}
/**
* 刪除操作 REST風格
*
*/
@RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
@ResponseBody
public String delete(@PathVariable("id") Long id) {
System.out.println("---------------------------delete:" + id);
return "delete";
}
/**
* 更新操作 REST風格
*
*/
@RequestMapping(value = "/user/update", method = RequestMethod.PUT)
@ResponseBody
public String update(User user) {
String result = JSON.toJSONString(user);
System.out.println("---------------------------Put:" + result);
return result;
}
/**
* 傳統風格 : /user?name戶zhangsan&age=18
*
*/
@RequestMapping(value = "/user", method = RequestMethod.GET)
@ResponseBody
public String search(@RequestParam("name") String queryString) {
System.out.println("---------------------------get:" + queryString);
return queryString;
}
}