06【SpringMVC的Restful支持】

news2024/10/6 1:38:45

文章目录

  • 六、SpringMVC的Restful支持
    • 6.1 RESTFUL示例:
    • 6.2 基于restful风格的url
    • 6.3 基于Rest风格的方法
    • 6.4 配置HiddenHttpMethodFilter
    • 6.5 Restful相关注解


六、SpringMVC的Restful支持

REST(英文:Representational State Transfer,即表述性状态传递,简称REST)RESTful是一种软件架构风格、设计风格,而不是标准,只是提供了一组设计原则和约束条件。它主要用于客户端和服务器交互类的软件。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。

6.1 RESTFUL示例:

示例请求方式效果
/user/1GET获取id=1的User
/user/1DELETE删除id为1的user
/userPUT修改user
/userPOST添加user

请求方式共有其中,其中对应的就是HttpServlet中的七个方法:

在这里插入图片描述

Tips:目前我们的jsp、html,都只支持get、post。

6.2 基于restful风格的url

  • 添加

URL:

http://localhost:8080/user

请求体:

{"username":"zhangsan","age":20}

提交方式: post

  • 修改
http://localhost:8080/user/1
  • 请求体:
{"username":"lisi","age":30}

提交方式:put

  • 删除
http://localhost:8080/user/1

提交方式:delete

  • 查询
http://localhost:8080/user/1

提交方式:get

6.3 基于Rest风格的方法

  • 引入依赖:
<dependencies>
    <!--包含Spring环境和SpringMVC环境-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.9.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-api</artifactId>
        <version>8.5.71</version>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.18</version>
    </dependency>
</dependencies>
  • 实体类:
package com.dfbz.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class City {
    private Integer id;         // 城市id
    private String cityName;    // 城市名称
    private Double GDP;         // 城市GDP,单位亿元
    private Boolean capital;    // 是否省会城市
}
  • 测试代码:
package com.dfbz.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
@Controller
@RequestMapping("/city")
public class CityController {

    /**
     * 新增
     */
    @PostMapping
    public void save(HttpServletResponse response) throws IOException {
        response.getWriter().write("save...");
    }

    /**
     * 删除
     *
     * @param id
     * @param response
     * @throws IOException
     */
    @DeleteMapping("/{id}")
    public void delete(@PathVariable Integer id, HttpServletResponse response) throws IOException {
        response.getWriter().write("delete...id: " + id);
    }

    /**
     * 修改
     *
     * @param id
     * @param response
     * @throws IOException
     */
    @PutMapping("/{id}")
    public void update(@PathVariable Integer id, HttpServletResponse response) throws IOException {
        response.getWriter().write("update...id: " + id);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @param response
     * @throws IOException
     */
    @GetMapping("/{id}")
    public void findById(@PathVariable Integer id, HttpServletResponse response) throws IOException {
        response.getWriter().write("findById...id: " + id);
    }
}

注意:restful风格的请求显然与我们之前的.form后置的请求相悖,我们把拦截规则更换为:/

  • 准备一个表单:
  • Demo01.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<h3>新增</h3>
<form action="/city" method="post">
    <input type="submit">
</form>

<h3>删除</h3>
<form action="/city/1" method="post">
    <%--建立一个名为_method的一个表单项--%>
    <input type="hidden" name="_method" value="delete">
    <input type="submit">
</form>

<h3>修改</h3>
<form action="/city/1" method="post">
    <input type="hidden" name="_method" value="put">
    <input type="submit">
</form>

<h3>查询</h3>
<form action="/city/1" method="get">
    <input type="submit">
</form>
</body>
</html>

6.4 配置HiddenHttpMethodFilter

默认情况下,HTML页面中的表单并不支持提交除GET/POST之外的请求,但SpringMVC提供有对应的过滤器来帮我们解决这个问题;

在web.xml中添加配置:

<filter>
    <filter-name>methodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>methodFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

相关源码:

public class HiddenHttpMethodFilter extends OncePerRequestFilter {
    private static final List<String> ALLOWED_METHODS;
    public static final String DEFAULT_METHOD_PARAM = "_method";
    private String methodParam = "_method";

    public HiddenHttpMethodFilter() {
    }

    public void setMethodParam(String methodParam) {
        Assert.hasText(methodParam, "'methodParam' must not be empty");
        this.methodParam = methodParam;
    }

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        HttpServletRequest requestToUse = request;
        if ("POST".equals(request.getMethod()) && request.getAttribute("javax.servlet.error.exception") == null) {
            // 获取request中_method表单项的值
            String paramValue = request.getParameter(this.methodParam);
            if (StringUtils.hasLength(paramValue)) {
                
                // 全部转换为大写(delete--->DELETE)
                String method = paramValue.toUpperCase(Locale.ENGLISH);
                if (ALLOWED_METHODS.contains(method)) {
                    requestToUse = new HiddenHttpMethodFilter.HttpMethodRequestWrapper(request, method);
                }
            }
        }

        filterChain.doFilter((ServletRequest)requestToUse, response);
    }

    static {
        ALLOWED_METHODS = Collections.unmodifiableList(Arrays.asList(HttpMethod.PUT.name(), HttpMethod.DELETE.name(), HttpMethod.PATCH.name()));
    }

    private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {
        private final String method;

        public HttpMethodRequestWrapper(HttpServletRequest request, String method) {
            
            // 修改request自身的的method值
            super(request);
            this.method = method;
        }

        public String getMethod() {
            return this.method;
        }
    }
}

6.5 Restful相关注解

  • @GetMapping:接收get请求
  • @PostMapping:接收post请求
  • @DeleteMapping:接收delete请求
  • @PutMapping:接收put请求

修改后的CityController:

package com.dfbz.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("/city")
public class CityController_RestFul {

    /**
     * 新增
     */
    @PostMapping
    public void save(HttpServletResponse response) throws IOException {

        response.getWriter().write("save...");
    }

    /**
     * 删除
     *
     * @param id
     * @param response
     * @throws IOException
     */
    @DeleteMapping("/{id}")
    public void delete(@PathVariable Integer id, HttpServletResponse response) throws IOException {
        response.getWriter().write("delete...id: " + id);
    }

    /**
     * 修改
     * @param id
     * @param response
     * @throws IOException
     */
    @PutMapping("/{id}")
    public void update(@PathVariable Integer id, HttpServletResponse response) throws IOException {

        response.getWriter().write("update...id: " + id);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @param response
     * @throws IOException
     */
    @GetMapping("/{id}")
    public void findById(@PathVariable Integer id, HttpServletResponse response) throws IOException {
        response.getWriter().write("findById...id: " + id);
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/52504.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

.vcxproj.filters 误删后如何重建

背景&#xff1a; 今天碰到这样一种情况&#xff0c;我在删除这个VS文件夹下的.user文件时&#xff0c;不小心把.vcxproj.filters也删除了。当然为什么删.user呢&#xff0c;因为换电脑了。 删除之后&#xff0c;我发现&#xff1a;我的解决方案目录变成这样了&#xff1a; 对…

基于springboot企业客户信息反馈平台设计与实现的源码+文档

摘 要 网络的广泛应用给生活带来了十分的便利。所以把企业客户信息反馈管理与现在网络相结合&#xff0c;利用java技术建设企业客户信息反馈平台&#xff0c;实现企业客户信息反馈的信息化。则对于进一步提高企业客户信息反馈管理发展&#xff0c;丰富企业客户信息反馈管理经…

数据分析:从界定问题开始做数据分析?

一、引言 “界定问题”是数据分析工作流程的第一步,也是最重要的一步。再怎么强调“界定问题”的重要性都不为过,因为一旦没有把问题界定清楚,后续的工作很可能将会南辕北辙。而如果我们将问题界定清楚,就能针对性的制定解决方案。 1.什么是界定问题 界定问题是一个需求…

黄健翔质疑半自动越位技术?用「技术流」解读卡塔尔世界杯

昨天&#xff0c;喀麦隆3比3塞尔维亚的比赛&#xff0c;黄健翔发微博质疑「半自动越位识别技术」太慢&#xff0c;而且没有考虑观众的需求&#xff0c;严重影响看球的体验&#xff0c;巴西和瑞士的比赛&#xff0c;黄健翔连发三条微博&#xff0c;再次吐槽VAR技术对足球带来的伤…

Qt | QTextCodec类使用详解、GBK和UTF8编码互转、QString的toLocal8bit和toLatin1区别

Qt | QTextCodec类使用详解、GBK和UTF8编码互转、QString的toLocal8bit和toLatin1区别 目录Qt | QTextCodec类使用详解、GBK和UTF8编码互转、QString的toLocal8bit和toLatin1区别1、QTextCodec简介及使用1.1 编码之间的转换1.2 解决中文显示乱码问题2、QString的toLocal8bit和t…

Python——基本数据类型的转换

1、为什么需要左数据类型的转换 2、转换为整形&#xff1a; 浮点类型转换为整形&#xff1a; a 3.14 b int(a) print(b) 浮点类型转换成整形的规则是&#xff1a;保留小数点前面的数&#xff0c;去掉小数点和小数点后面的数。 字符串转换成整形&#xff1b; a 123 b int(a…

PHP怎么实现实时聊天?GatewayWorker+Thinkphp5即时通讯系统实现

PHP怎么实现实时聊天&#xff1f;GatewayWorkerThinkphp5即时通讯系统实现 一、项目介绍 后端技术&#xff1a;thinkphp5fastadmingatewayworker 前端技术&#xff1a;jqueryhtmlcsswebsocket 项目实现了简单的登录、注册功能&#xff0c;会员可进行后台管理&#xff0c;主界…

[OpenCV实战]52 在OpenCV中使用颜色直方图

颜色直方图是一种常见的图像特征&#xff0c;顾名思义颜色直方图就是用来反映图像颜色组成分布的直方图。颜色直方图的横轴表示像素值或像素值范围&#xff0c;纵轴表示该像素值范围内像素点的个数或出现频率。颜色直方图属于计算机视觉中的基础概念&#xff0c;其常常被应用于…

Ceres库中参数理解

1 参数含义 2 参考链接 Modeling Non-linear Least Squares — Ceres Solver (ceres-solver.org) Ceres详解&#xff08;二&#xff09; CostFunction_他人是一面镜子&#xff0c;保持谦虚的态度的博客-程序员宝宝_ceres costfunction - 程序员宝宝 (cxybb.com)

Linux基础知识与实操-篇七:用户身份切换与特殊控制

文章目录使用者身份的切换配置sudo单一用户群组处理有限制的命令操作特殊shell与PAM模块Linux用户信息传递与当前系统上其他用户对话建立大量账号最后在理解了前篇 篇六:用户权限控制与账号管理 后&#xff0c;我们继续深入用户权限控制关于用户身份切换、限制特殊权限相关的内…

一步步带你用react+spring boot搭建后台之二(登录与首页篇)

前言 最近半年一直在重庆忙于项目上的事情&#xff0c;博客停更了好久&#xff0c;一直想写2个开源项目: 一个是入门级&#xff1a;一步步带你用reactspring boot搭建后台 一个是olap应用系列&#xff1a;一步步构建olap分析平台 今天开始写第一个系列&#xff0c;完整代码随…

LDO(线性稳压器)设计检查

原理图设计规范检查——LDO&#xff08;线性稳压器&#xff09;设计检查 LDO基本概念&#xff1a; LDO即low dropout regulator&#xff0c;是一种低压差线性稳压器&#xff0c;这是相对于传统的线性稳压器来说的。传统的线性稳压器&#xff0c;如78XX系列的芯片都要求输入电…

Linux cifs挂载远程windows共享目录

Linux cifs挂载远程windows共享目录共享windows目录开启共享权限共享磁盘或目录Linux 先决条件安装Linux依赖开启Administrator 用户使用Username/Password挂载临时挂载自动挂载使用Credentials挂载创建CIFS Windows共享凭证文件临时挂载自动挂载终止挂载共享windows目录 开启…

“算力时代”奔涌而来,JASMINER茉莉发布能效更强劲的X16-Q

11月26日&#xff0c;JASMINER茉莉发布X16系列首款静音型算力产品X16-Q&#xff0c;并同步开启全球预售&#xff0c;将为行业带来更高效、更绿色、更智能的智慧算力。 JASMINER X16相较X4系列产品迎来了全新的“进化”&#xff0c;除去新一代JASMINER茉莉自研高通量芯片的应用…

百看不如一练系列 32个python实战项目列表,得不到就毁掉

前言&#xff1a; 不管学习哪门语言都希望能做出实际的东西来&#xff0c;这个实际的东西当然就是项目啦&#xff0c;不用多说大家都知道学编程语言一定要做项目才行。 这里整理了32个Python实战项目列表&#xff0c;都有完整且详细的教程&#xff0c;你可以从中选择自己想做…

Day2多种抓包工具介绍以及使用封包监听工具找到挑战数据包实现发送数据包进行挑战

工具相关证书安装指南 Charles https://blog.csdn.net/weixin_45459427/article/details/108393878 Fidder https://blog.csdn.net/weixin_45043349/article/details/120088449 BurpSuite https://blog.csdn.net/qq_36658099/article/details/81487491 Fiddler&#xff1a; 是一…

PyQt5 不规则窗口的显示

PyQt5 不规则窗口的显示QPixmap和QBitmap绘图的效果对比不可以拖动的不规则窗口可以拖动的不规则窗口不规则窗口实现动画效果加载GIF动画效果函数描述setMask(self, QBitmap)setMask(self, QRegion)setMask()的作用是为调用它的控件增加一个遮罩&#xff0c;遮住所选区域以外的…

【Android App】实战项目之仿微信的附近的人(附源码和演示 超详细)

需要全部源码请点赞关注收藏后评论区留言私信~~~ 艺术家常说“距离产生美”&#xff0c;其实距离近才是优势&#xff0c;谁不希望自己的工作事少钱多离家近呢&#xff1f;不光是工作&#xff0c;像租房买房、恋爱交友&#xff0c;大家都希望找个近点的&#xff0c;比如58、赶集…

【react-笔记】

目录简介基本使用虚拟dom的两种创建方法jsx语法规则模块与组件、模块化和组件化的理解模块组件模块化组件化函数式组件类式组件组件实例三大属性statepropsrefs事件处理包含表单的组件分类非受控组件受控组件高阶函数_函数的柯里化生命周期引出生命周期理解生命周期(旧)总结新的…

Verilog 延迟反标注

延迟反标注&#xff0c; SDF 延迟反标注是设计者根据单元库工艺、门级网表、版图中的电容电阻等信息&#xff0c;借助数字设计工具将延迟信息标注到门级网表中的过程。利用延迟反标注后的网表&#xff0c;就可以进行精确的时序仿真&#xff0c;使仿真更接近实际工作的数字电路…