# 8RESTful开发风格

传统web应用的问题: 传统web应用的问题 基于传统的mvc模式开发的web应用,有三个重要的组件:Sevlet(Controller)、JSP(View)、Java Beans(Model),其中Sevlet起到控制器的作用,用来接收前端浏览器发送的请求数据,之后再去后台去查询对应的结果数据,也就是生成model,之后再将model中的数据与View(JSP||Freemarker)进行渲染,从而得到html,返回给浏览器。这种开发模式固然没有问题,但是作为JSP输出的肯定是HTML,那就意味着我们的客户端必然是支持html的浏览器,而现在互联网呈现多元化的趋势,除了像浏览器这样的B/S客户端,还有诸如像微信小程序、APP等各种客户端,像这种客户端是不支持HTML的,这时候就出现了REST与RESTful这样的开发风格

# 导航

回到Spring MVC导航页

# REST与RESTful

  • REST-表现层状态转换,资源在网络中以某种表现形式进行状态转移(比如:图片、css、js以url的形式)
  • RESTful-是基于REST理念的一套开发风格,是具体的开发规则

# RESTful传输数据

RESTful数据传输

RESTful只返回JSON||XML这样的内容,不返回与展现相关的内容,如何展现是客户端的关注,后端只关心后端数据。

# RESTful开发规范

  • 使用URL作为用户交互入口
  • 明确的语义规范(GET|POST|PUT|DELETE)
    • 在web情况下(浏览器)只支持get和POST
    • GET:查询操作
    • POST:新增操作
    • PUT:更新操作
    • DELETE:删除操作
  • 只返回数据(JSON|XML),不包含任何展现

# RESTful命名要求

URI 说明 修改建议
GET /articles?au=lily 正确语法
GET /a/1 URI必须具有语义 GET /student/1
POST /createArticle/1 URI必须使用名词 POST /article/1
GET /articles/author/1 URI扁平化,不超两级 GET /articles/author?id=1
DELETE /articles/1 URI名词区分单复数 GET /articles?au=lily DELETE /article/1

# 开发RESTful Web应用

目录如下

IDEA创建一个新的maven工程,创建成功后,设置maven工程为标准web工程:File-->Project Structure-->Facets--> 可以参照如下文章: 2idea环境下创建MavenWebApp

ajax乱码解决方案:

ajax乱码解决

在applicationContext.xml文件中-->mvc:annotation-driven-->mvc:message-converters-->增加

 <value>application/json;charset=utf-8</value>
1

applicationContext.xml文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mv="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--
context:component-scan 标签的作用:
在Spring IOC初始化过程中,自动创建并管理com.torey.springmvc包及子包中拥有以下注解的对象:
@Repository  、@Service 、@Controller  、@Component
    -->
    <context:component-scan base-package="com.torey.restful"></context:component-scan>
    <!--启用Spring MVC的注解开发模式-->
    <!--<mvc:annotation-driven/>-->
    <!--conversion-service="converterServer"是转换类-->
    <mvc:annotation-driven>
        <!--mvc:message-converters:是消息转换器-->
        <mvc:message-converters>
            <!--StringHttpMessageConverter:对http响应中的文本进行转换StringHttpMessageConverter-->
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <!--spring mvc解决响应中的乱码:底层调用的也是servlet中response.setContentType("text/html;charset=utf-8")-->
                        <value>text/html;charset=utf-8</value>
                        <value>application/json;charset=utf-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    <!--将图片/JS/CSS等静态资源排除在外,可提高执行效率-->
    <mvc:default-servlet-handler/>
</beans>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

在没一个方法上面都加上@ResponseBody,特别繁琐,可以在类上面加上@RestController注解

package com.torey.restful.controller;

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

/**
 * @Author http://torey611.gitee.io/li-tao-feng/
 * @Email torey6061@qq.com
 * @Date 2021/5/22 10:55
 * @描述:
 */
@Controller
@RequestMapping("/restful")
public class RestfulController {
    @ResponseBody
    @GetMapping("/request")
    public String doGetRequest(){
        return "{\"message\": \"GET请求\"}";
    }
    @ResponseBody
    @PostMapping("/request")
    public String doPostRequest(){
        return "{\"message\": \"Post请求\"}";
    }
    @ResponseBody
    @PutMapping("/request")
    public String doPutRequest(){
        return "{\"message\": \"Put请求\"}";
    }
    @ResponseBody
    @DeleteMapping("/request")
    public String doDeleteRequest(){
        return "{\"message\": \"delete请求\"}";
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<input type="text" id="textDomId" />
<button onclick="ajaxTest('get')">get请求</button>
<button  onclick="ajaxTest('post')">post请求</button>
<button  onclick="ajaxTest('put')">put请求</button>
<button onclick="ajaxTest('delete')">delete请求</button>
</body>
<script>
    function ajaxTest(typeStr){
        $.ajax({
            url:"/restful/request",
            type:typeStr,
            dataType:"json",
            success:function(result){
                $("#textDomId").val(result.message);
            }});
    }
</script>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

# 导航,上一页,下一页

7SpringMVC整合Freemarker
9RestController注解与路径变量

# 支持我-微信扫一扫-加入微信公众号

Aseven公众号

# 赞赏作者

赞赏作者

# 种一棵树,最好的时间是十年前,其次是现在

立志用功,如种树然。方其根芽,犹未有干;及其有干,尚未有枝;枝而后叶,叶而后花、实。初种根时,只管栽培灌溉,勿作枝想,勿作实想。悬想何益?何不忘栽培之功,怕没有枝叶花实?