Spring boot REST 风格概述、@InitBinder 格式化日期参数
发布日期:2021-06-23 19:02:33 浏览次数:14 分类:技术文章

本文共 5666 字,大约阅读时间需要 18 分钟。

目录


REST 风格概述

1、HTTP 协议是一个广泛应用的 Internet 协议,提供了8个不同的请求方法(常见的是前 4 个):

请求方式 描述
GET  向特定资源发出请求(请求指定页面信息,并返回实体主体)
POST 向指定资源提交数据进行处理请求(提交表单、上传文件)
PUT 向指定资源位置上上传其最新内容
DELETE 请求服务器删除指定的资源
HEAD  
OPTIONS  
TRACE  
CONNECT  

2、REST 全称 Representational State Transfer ——(资源)表现层状态转化,是目前最流行的一种互联网软件架构。它结构清晰、符合标准、易于理解、扩展方便, 所以正得到越来越多网站的采用。

3、REST 风格就是通过 Http 请求方式的不同来标识不同的方法,即对于同一个请求路径,可以根据请求方式的不同来区分它们

操作 普通CRUD(根据uri区分)               REST风格CRUD(根据请求方式区分)        
查询 localhost:8080/tiger/findUsers localhost:8080/tiger/user-----get方式请求
添加 localhost:8080/tiger/saveUser localhost:8080/tiger/user-----post方式请求
修改 localhost:8080/tiger/updateUser localhost:8080/tiger/user-----pup方式请求
删除 localhost:8080/tiger/deleteUser localhost:8080/tiger/user-----delete方式请求

4、不能完全一概而论谁优谁劣,有时候习惯就好,举例如下:

操作 举例
查询所有用户     @GetMapping("user")
    public String findUsers(Model model) {
根据 id 查询用户     @GetMapping("user/{id}")
    public String findUserById(@PathVariable(name = "id") Integer id, Model model) {
添加用户     @PostMapping("user")
    public String saveUser(User user) {
修改用户     @PutMapping("user")
    public String updateUser(User user) {
根据 id 删除用户     @DeleteMapping("user/{id}")
    public String deleteUser(@PathVariable(name = "id") Integer id) {

form 表单发起 put 请求

1、form 表单的 method  属性值只有 get 与 post 两种,所以 form 表单使用 put、delete 等其它请求方式时,需要特殊处理。

1)表单 method 属性值仍然指定为 post。

2)表单中创建一个隐藏的 input 项,name 属性值强制为 "_method",value 属性值指定此 form 请求的具体方式,如 put、delete 等

2、如果使用类似的方式,则可以使用它的 type 属性直接指定请求方式,如 type: put。

3、环境:Java jdk 1.8 +Spring boot 2.1.3 + Thymeleaf。

4、后台接口如下,主要用于模拟向页面传递数据与接收数据:

import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.ObjectMapper;import com.wmx.thymeleafapp.pojo.User;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PutMapping;import org.springframework.web.bind.annotation.ResponseBody;import java.util.Date;/** * @author wangmaoxiong * @version 1.0 * @date 2020/5/7 9:12 */@Controllerpublic class ExampleController {    /**     * 跳转到修改页面,get 请求: http://localhost:8080/example/httpPut     *     * @return     */    @GetMapping("example/httpPut")    public String toPutPage(Model model) {        //待修改人员数据        User user = new User(9527, "华安", 18990.98F, "本科", new Date());        //学历下拉框数据        String[] educationArr = {"研究生及以上", "本科", "大专", "高中", "初中及以下"};        //往前端传递数据.        model.addAttribute("user", user);        model.addAttribute("educationArr", educationArr);        return "examples/httpPut";    }    /**     * 修改提交时调用此接口, put 请求:  http://localhost:8080/example/httpPut     *     * @param user     * @return     */    @PutMapping("example/httpPut")    @ResponseBody    public String httpPut(User user) {        //将数据返回给页面,不操作数据.        String valueAsString = "{}";        try {            ObjectMapper objectMapper = new ObjectMapper();            valueAsString = objectMapper.writeValueAsString(user);        } catch (JsonProcessingException e) {            e.printStackTrace();        }        return valueAsString;    }}

5、前端修改页面如下,使用 Thymeleaf 处理数据,使用 form 表单发送 put 请求(其它 delete 请求方式也是同理):

    
Http Put 方式请求
姓名:
薪水:
学历:
生日:

在线演示源码:

@InitBinder 格式化日期参数

1、页面提交的日期参数,Spring MVC 会自动转换成 Date 类型,默认支持 "/" + ":" 分隔的方式,即年月日必须是 "/" 分割,时分秒必须是 ":" 分割,如 1993/08/25 08:12:22,否则报错: Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'

2、 默认配置如下,spring.mvc.date-format 默认使用 "/" 格式,如果需要使用其它格式,则在全局配置文件中覆盖即可,如:spring.mvc.date-format=yyyy-MM-dd HH:mm:ss

# SPRING MVC (WebMvcProperties)spring.mvc.async.request-timeout= # Amount of time before asynchronous request handling times out.spring.mvc.contentnegotiation.favor-parameter=false # Whether a request parameter ("format" by default) should be used to determine the requested media type.spring.mvc.contentnegotiation.favor-path-extension=false # Whether the path extension in the URL path should be used to determine the requested media type.spring.mvc.contentnegotiation.media-types.*= # Map file extensions to media types for content negotiation. For instance, yml to text/yaml.spring.mvc.contentnegotiation.parameter-name= # Query parameter name to use when "favor-parameter" is enabled.spring.mvc.date-format= # Date format to use. For instance, `dd/MM/yyyy`.spring.mvc.dispatch-trace-request=false # Whether to dispatch TRACE requests to the FrameworkServlet doService method.

3、除了在配置文件中指定,也可以使用 org.springframework.web.bind.WebDataBinder API 转换日期。

/**     * 自定义日期转换器     * Spring3.0 之前是会自动转换的,但是 3.0 之后需要程序员自己转换     * 直接将 @InitBinder... 注解的方法放置在 @Controller 中即可     *     * @param dataBinder     */    @InitBinder    public void initBind(WebDataBinder dataBinder) {       /**指定日期格式*/        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss");        /**指定日期/时间解析是否不严格         * lenient - 为 true 时,解析过程是不严格的         */        dateFormat.setLenient(true);        /**Date.class:表示这是注册的是日期类型         * new CustomDateEditor(dateFormat, true):true 表示允许为空         */        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));    }

4、无论是 spring.mvc.date-format 还是 WebDataBinder 都需要注意:

1)假如指定格式为 yyyy-MM-dd ,则传入的日期字符串只能是 "-" 分割,如果传入 1993/08/25 则报错

2)假如指定格式为 yyyy-MM-dd ,则传入 1993-08-25 12:08:25 时,时分秒会强制为0,如 1993-08-25 00:00:00
3)假如指定格式为 yyyy-MM-dd HH:mm:ss,则必须同时传入时分秒,否则报错,如传入 1993-08-15 则报错.

在线源码:

 

 

 

转载地址:https://wangmaoxiong.blog.csdn.net/article/details/81290645 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Swift基础-0002
下一篇:Swift基础-0001

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2024年04月08日 10时16分39秒