栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring MVC REST风格

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring MVC REST风格

REST(Representational State Transfer)即表述性转移,是目前最流行的一种软件架构风格。它结构清晰、易于理解、有较好的扩展性。
REST 概念较为复杂,我们不过多解释,大家简单了解 Spring MVC 的 REST 风格的简单使用即可。

Spring REST 风格可以简单理解为:使用 URL 表示资源时,每个资源都用一个独一无二的 URL 来表示,并使用 HTTP 方法表示操作,即准确描述服务器对资源的处理动作(GET、POST、PUT、DELETE),实现资源的增删改查。
GET:表示获取资源
POST:表示新建资源
PUT:表示更新资源
DELETE:表示删除资源

下面举例说明 REST 风格的 URL 与传统 URL 的区别。
/userview.html?id=12 VS /user/view/12
/userdelete.html?id=12 VS /user/delete/12
/usermodify.html?id=12 VS /user/modify/12

我们发现 REST 风格的 URL 中最明显的就是参数不再使用“?”传递。这种风格的 URL 可读性更好,使得项目架构清晰,最关键的是 Spring MVC 也提供对这种风格的支持。

但是也有弊端,对于国内项目,URL 参数有时会传递中文,而中文乱码是一个令人头疼的问题,所以我们应该根据实际情况进行灵活处理。很多网站都是传统 URL 风格与 REST 风格混搭使用。
示例
由于 HTTP 不支持 PUT 和 DELETE 请求,所以需要将 DELETE 和 PUT 请求转换成 POST 请求,在 web.xml 中配置过滤器 HiddenHttpMethodFilter。



    hiddenHttpMethodFilter
    org.springframework.web.filter.HiddenHttpMethodFilter


    hiddenHttpMethodFilter
    /*

新建 rest.jsp 代码如下。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




REST风格


    

发送GET请求

GET

发送POST请求

发送PUT请求

发送DELETE请求

下面通过 @RequestMapping 映射请求中的 method 参数实现四种请求方式的调用,UserController 代码如下。

package net.biancheng.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;
@Controller
public class UserController {
    @RequestMapping("/torest")
    public String torest() {
        return "rest";
    }
    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    public String hello(@PathVariable Integer id) {
        System.out.println("test rest get:" + id);
        return "success";
    }
    @RequestMapping(value = "/user/{id}", method = RequestMethod.POST)
    public String hello() {
        System.out.println("test POST:");
        return "success";
    }
    @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
    public String helloDelete(@PathVariable Integer id) {
        System.out.println("test rest delete:" + id);
        return "success";
    }
    @RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
    public String helloPUt(@PathVariable Integer id) {
        System.out.println("test rest put:" + id);
        return "success";
    }
}

访问地址:http://localhost:8080/springmvcDemo2/torest,运行结果如下。

依次点击请求按钮,控制器输出结果如下。
test rest get:1
test POST:
test rest put:1
test rest delete:1

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/933586.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号