转自:
Spring MVC 如何开发REST风格的应用呢?
REST(Representational State Transfer):表述性转移,是目前最流行的一种软件架构风格。它结构清晰、易于理解、有较好的扩展性。
Spring REST 风格:使用 URL 表示资源时,每个资源都可以使用一个独一无二的 URL 来表示,
并采用HTTP 方法进行操作,即 (GET、POST、PUT、DELETE),实现资源的增删改查。
GET: 获取资源
POST: 新建资源
PUT: 更新资源
DELETE: 删除资源
例:传统风格同REST风格URL对比
/cusview.html?id=88 VS /user/view/88
/cusdelete.html?id=88 VS /user/delete/88
/cuschange.html?id=88 VS /user/change/88
例:
在web.xml中配置过滤器 HiddenHttpMethodFilter
使其支持PUT和DELETE请求
如下所示:
hiddenHttpMethodFilterorg.springframework.web.filter.HiddenHttpMethodFilter
hiddenHttpMethodFilter/*
新建一个REST请求页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
REST风格 发送GET请求
GET 发送POST请求
发送PUT请求
发送DELETE请求
编写Controller
package com.java265.controller;
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;
public class CusController {
@RequestMapping(value = "/cus/{id}", method = RequestMethod.GET)
public String hello(@PathVariable Integer id) {
System.out.println("test rest get:" + id);
return "success";
}
@RequestMapping(value = "/cus/{id}", method = RequestMethod.POST)
public String hello() {
System.out.println("test POST:");
return "success";
}
@RequestMapping(value = "/cus/{id}", method = RequestMethod.DELETE)
public String helloDelete(@PathVariable Integer id) {
System.out.println("test rest delete:" + id);
return "success";
}
@RequestMapping(value = "/cus/{id}", method = RequestMethod.PUT)
public String helloPut(@PathVariable Integer id) {
System.out.println("test rest put:" + id);
return "success";
}
}