SpringMVC中JSON数据的设置、RestFul风格

Java知识点总结:想看的可以从这里进入

3.4、JSON数据

3.4.1、前端使用

前端在JavaScript中有封装的JSON对象,可以直接用来操作JSON数据。

  • 将对象转化成JSON数据

    JSON.stringify(对象名);
    
  • 将JSON转化为对象:

    JSON.parse(JSON数据名);
    
3.4.2、后端使用

前端可以直接使用,但是在后端使用JSON数据,需要引入第三方来实现快捷的操作,比如:Jackson、fastjson等,在使用前需要先导入相应的依赖。

1、Jackson

这种方式最好是创建一个专门的Util类,来辅助我们使用JSON数据

  1. 添加依赖

    <!--Jackson的依赖-->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.12.4</version>
    </dependency>
    
  2. 创建Util类

    public class JSONUtil {
        public static String getJSON(Object o) throws JsonProcessingException {
            return getJSON(o,"yyyy-MM-dd hh:mm:ss");
        }
        //将对象封装成JSON格式的数据
        public static String getJSON(Object o,String dateFormat) throws JsonProcessingException {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
            SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
            mapper.setDateFormat(sdf);
            return mapper.writeValueAsString(o);
        }
    }
    
  3. 测试

    @RequestMapping("f1")
    @ResponseBody
    public String JSONTest() throws JsonProcessingException {
        User user1 = new User(1,"张三");
        User user2 = new User(2,"李四");
        List<User> userList = new ArrayList<>();
        userList.add(user1);
        userList.add(user2);
    
        return JSONUtil.getJSON(userList);
    }
    
image-20210805181111492

当然除了创建Util帮助类外,还可以利用Spring的消息转换机制 配置 MappingJackson2HttpMessageConverter,他会自动将返回的对象转化为JSON格式数据。

<!--配置JSON格式的转换器-->
<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    <property name="supportedMediaTypes">
        <list>
            <value>application/json;charset-UTF-8</value>
        </list>
    </property>
</bean>

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jsonConverter"/>
        </list>
    </property>
</bean>
image-20230301205737244
2、fastjson

fastjson有三个重要的类:JSONObject(代表JSON对象),JSONArray(代表JSON数组),JSON(JSONObject和JSONArray的转化),

  1. 添加依赖

    <!--fastjson的依赖-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.76</version>
    </dependency>
    
  2. 测试

    //List对象转化成JSON字符串
    JSON.toJSONString(userList);
    //对象转化成JSON字符串
    JSON.toJSONString(user1);
    //JSON转化成List
    List<User> userList1 = JSON.parseArray(s, User.class);
    //JSON转化成对象
    User user = JSON.parseObject(s1, User.class);
    

    image-20220915181441660

    image-20220916101529650

3.5、RestFul风格

3.5.1、简介

RestFul(Representational State Transfer,表现层资源状态转移。)风格是一种当前比较流行的互联网软件架构模式,它利用HTTP 协议的特性,规定了一套资源获取的方式,,它可以使软件更简洁,更有层次,易于实现缓存等机制。

在 web开发中,Rest使用HTTP协议连接器来标识对资源的操作,用 HTTP GET标识获取查询资源,HTTP POST标识创建资源,HTTP PUT标识修改资源,HTTP DELETE标识删除资源,这样就构成了 Rest风格数据处理的核心,它的增删改查在在Controller中通过四种注解来区分(也可以用@RequestMapping的属性method):

资源操作对应注解HTTP 请求方式
获取资源(SELECT)@GetMapping、
@RequestMapping(value = “”,method = RequestMethod.GET)
GET
新增资源(INSERT)@PostMapping
@RequestMapping(value = “”,method = RequestMethod.POST)
POST
修改资源(UPDATE)@PutMapping
@RequestMapping(value = “”,method = RequestMethod.PUT)
PUT
删除资源(DELETE)@DeleteMapping
@RequestMapping(value = “”,method = RequestMethod.DELETE)
DELETE
  • 传统的资源操作是通过 ? & 等符号将参数拼接起来的,如果要区分提交、删除等操作,是用不同的请求路径完成的

    获取:http://localhost:8080/getUserById?id=1

    修改:http://localhost:8080/updateUser?id=1

    新增:http://localhost:8080/insertUser?id=1

    删除:http://localhost:8080/deleteUserById?id=1

    @Controller
    public class RestfulController {
        @RequestMapping("getUserById")
        public String getUserById(int id, Model model){
        }
        @RequestMapping("updateUser")
        public String updateUser(int id, Model model){
        }
        @RequestMapping("insertUser")
        public String insertUser(int id, Model model){
        }
        @RequestMapping("deleteUserById")
        public String deleteUserById(int id, Model model){
        }
    }
    
  • RestFul 是将参数作为 URL 的一部分发送到服务器中,它的增删改查的路径可以是一样的

    http://localhost:8080/user/1

    @Controller
    public class RestfulController {
        @GetMapping("/user/{id}")
        public String getUserById(@PathVariable("id")int id, Model model){
        }
        @PostMapping("/user/{id}")
        public String updateUser(@PathVariable("id")int id, Model model){
        }
        @PutMapping("/user/{id}")
        public String insertUser(@PathVariable("id")int id, Model model){
        }
        @DeleteMapping("/user/{id}")
        public String deleteUserById(@PathVariable("id")int id, Model model){
        }
    }
    
3.5.2、使用

我们知道表单提交只要2 种方式:get和post,那么put和delete的提交怎么实现呢?

在Spring中提供了一个过滤器:HiddenHttpMethodFilter,它可以对请求进行过滤,可以将请求转换成HTTP方式,但是它的转换是有一定条件的:

  • 只能将Post的请求转换成 put 或 delete
  • 必须携带一个name为: _method 的参数。

在满足了以上条件后,HiddenHttpMethodFilter 过滤器就会根据请求参数 _method 的值,改变请求的方式,即请求参数 _method 的值才是最终的请求方式,因此我们需要在 POST 请求中携带一个名为 _method 的参数,参数值为 DELETE 或 PUT。

这个过滤器需要在 web.xml中进行配置:

<!--    Rest风格,URL路径映射(需要将这个过滤器配置在字符编码的过滤器之后才行)-->
<filter>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

在配置好过滤器后进行测试:

  1. 测试POST转为Put提交(测试Delete将_method的值改为DELETE即可)

    <form action="${pageContext.request.contextPath}/putTest" method="post">
        <!--用来将POST转为Put-->
        <input type="hidden" name="_method" value="PUT"/>
        <!--用来将POST转为DELETE-->
        <!--<input type="hidden" name="_method" value="DELETE"/>-->
        姓名:<input class="" id="name" name="name" size="50" type="text" value=""/>
        住址:<input class="" id="title" name="address" size="50" value="" type="text"/>
        年龄:<input class="" name="age" size="50" value="" type="text"/>
        介绍:<textarea name="information" class="" id="content" rows="10"/>
        <input class="" value="提交" type="submit"/>
        <input class="" onclick="history.go(-1)" value="返回" type="button"/>             
    </form>
    
    //put提交就意味着要修改资源,所以在实际操作中,会去service和dao中进行修改的操作
    @PutMapping("putTest")
    @ResponseBody
    public String putTest(User user, Model model){
        return String.format("姓名:%s,地址:%s,年龄:%s,介绍:%s",user.getName(),user.getAddress(),user.getAge(),user.getInformation());
    }
    
    image-20220916110904463

    image-20220916111005906

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

辰 羽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值