06【SpringMVC的Restful支持】
创始人
2024-03-08 12:45:59

文章目录

  • 六、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风格的方法

  • 引入依赖:
org.springframeworkspring-webmvc5.2.9.RELEASEorg.apache.tomcattomcat-api8.5.71org.projectlomboklombok1.18.18

  • 实体类:
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;         // 城市idprivate 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 {/*** 新增*/@PostMappingpublic 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" %>

Title

新增

删除

<%--建立一个名为_method的一个表单项--%>

修改

查询

6.4 配置HiddenHttpMethodFilter

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

在web.xml中添加配置:

methodFilterorg.springframework.web.filter.HiddenHttpMethodFilter

methodFilter/*

相关源码:

public class HiddenHttpMethodFilter extends OncePerRequestFilter {private static final List 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 {/*** 新增*/@PostMappingpublic 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);}
}

相关内容

热门资讯

猫咪吃了塑料袋怎么办 猫咪误食... 你知道吗?塑料袋放久了会长猫哦!要说猫咪对塑料袋的喜爱程度完完全全可以媲美纸箱家里只要一有塑料袋的响...
埃菲尔铁塔在哪 中国仿建埃菲尔... 2019年4月26日,广西南宁市,街头惊现一座巨型山寨版埃菲尔铁塔,高约20米,白色塔身,造型逼真,...
苗族的传统节日 贵州苗族节日有... 【岜沙苗族芦笙节】岜沙,苗语叫“分送”,距从江县城7.5公里,是世界上最崇拜树木并以树为神的枪手部落...
北京的名胜古迹 北京最著名的景... 北京从元代开始,逐渐走上帝国首都的道路,先是成为大辽朝五大首都之一的南京城,随着金灭辽,金代从海陵王...
世界上最漂亮的人 世界上最漂亮... 此前在某网上,选出了全球265万颜值姣好的女性。从这些数量庞大的女性群体中,人们投票选出了心目中最美...
应用未安装解决办法 平板应用未... ---IT小技术,每天Get一个小技能!一、前言描述苹果IPad2居然不能安装怎么办?与此IPad不...
长白山自助游攻略 吉林长白山游... 昨天介绍了西坡的景点详细请看链接:一个人的旅行,据说能看到长白山天池全凭运气,您的运气如何?今日介绍...
脚上的穴位图 脚面经络图对应的... 人体穴位作用图解大全更清晰直观的标注了各个人体穴位的作用,包括头部穴位图、胸部穴位图、背部穴位图、胳...
demo什么意思 demo版本... 618快到了,各位的小金库大概也在准备开闸放水了吧。没有小金库的,也该向老婆撒娇卖萌服个软了,一切只...
埃菲尔铁塔在哪 中国仿建埃菲尔... 2019年4月26日,广西南宁市,街头惊现一座巨型山寨版埃菲尔铁塔,高约20米,白色塔身,造型逼真,...
苗族的传统节日 贵州苗族节日有... 【岜沙苗族芦笙节】岜沙,苗语叫“分送”,距从江县城7.5公里,是世界上最崇拜树木并以树为神的枪手部落...
北京的名胜古迹 北京最著名的景... 北京从元代开始,逐渐走上帝国首都的道路,先是成为大辽朝五大首都之一的南京城,随着金灭辽,金代从海陵王...
应用未安装解决办法 平板应用未... ---IT小技术,每天Get一个小技能!一、前言描述苹果IPad2居然不能安装怎么办?与此IPad不...