06【SpringMVC的Restful支持】
创始人
2024-03-08 09:02:48
0

文章目录

  • 六、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);}
}

相关内容

热门资讯

公安机关悬赏征集2名台湾居民违... 国务院台办发言人彭庆恩24日在例行新闻发布会上表示,经公安机关侦查,台湾居民简文昇、陈顺进2人系走私...
昆明召开消费“三新”试点政策宣... 昆明信息港讯(昆明日报 记者缪亚平)12月22日,全市消费新业态新模式新场景试点政策宣讲会在昆明召开...
临县召开防治中小学生校园欺凌和... 12月24日下午,临县召开防治中小学生校园欺凌和预防未成年人违法犯罪专项行动动员会,县委常委、政法委...
河南省司法厅强化法律援助供给提... 河南省司法厅紧紧围绕党委、政府中心任务,认真谋划推进法律援助工作,深入贯彻实施法律援助法,强化服务供...
安徽铜陵:专业调解 激活基层治... “多亏你们居中协调,才能这么顺利解决问题!”近日,在铜陵市铜官区综治中心,市民孙先生对调解员高效协助...
强生爽身粉致癌案判赔女子约11... 据央视财经报道,当地时间12月22日,美国马里兰州陪审团作出一项裁定:强生公司需向一名因使用其婴儿爽...
牛市早报|央行:发挥增量政策和... 【市场数据】 截至12月24日收盘,上证综指涨0.53%,报3940.95点;科创50指数涨0.9%...
宁夏出台未成年人保护新规 学校... 本报讯(记者马学礼 李静楠)近日,宁夏回族自治区人大常委会表决通过《宁夏回族自治区实施〈中华人民共和...
央行货币政策委员会:加强货币政... 中国人民银行货币政策委员会2025年第四季度例会于12月18日召开。会议要求,要继续实施适度宽松的货...