搭建一个RESTful Web Service

在搭建之前,首先了解一下什么是RESTful,RESTful(Representational state transfer),它并不是一项新技术,而是一种接口规范。

为什么要用RESTful?

因为前后端分离主要是以API为界限进行解耦的,这就会产生大量的API,采用RESTful来统一规范更易于理解且达到解耦目的。
过去客户端向服务器请求资源的url如下:

GET /getStudents
GET /getStudent?id=''
POST /saveStudent
POST /updateStudent
POST /deleteStudent

可以看到,这些请求资源中的动词是没有必要的,如果用RESTful规范的请求,如下:

GET /Students
GET /Students/1 or /Students?id = 1 查找id为1的学生
POST /Student 保存学生
PUT /Student/1 修改学生
DELETE /Student/1 删除学生

RESTful规范规定,所有请求的对象都是资源,都有URI,URI中不能出现动词,只能是名词。


使用Spring来搭建一个简单的RESTful Web Service

我将要实现的效果是通过访问http://localhost:8080/greeting,浏览器返回JSON字符串如下:

{"id":1,"content":"Hello, World!"}

也可以通过访问http://localhost:8080/greeting?name='zdf',浏览器返回JSON字符串如下:

{"id":1,"content":"Hello, zdf!"}

OK, here we go!

step 1 通过maven导入相关包

这里我们使用到了Spring boot,所以需要导入Spring boot的相关jar包,注:Spring boot是简化配置而存在的(个人理解)。

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <scope>test</scope>
</dependency>
<plugin>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
        <artifactId>maven-clean-plugin</artifactId>
        <version>3.0.0</version>
</plugin>
<repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
    </repositories>
<pluginRepositories>
    <pluginRepository>
        <id>spring-releases</id>
       <url>https://repo.spring.io/libs-release</url>
    </pluginRepository>
</pluginRepositories>

step2 创建一个POJO类

POJO(plain old java object),我觉得它和JavaBean表面上没什么区别,都是Entity Class。

package hello;
/**
 * 描述:
 *
 * @author halo
 * @create 2018-06-30 13:14
 */
public class Greeting {
    private final long id;
    private final String greeting;

    public Greeting(long id, String greeting) {
        this.id = id;
        this.greeting = greeting;
    }

    public long getId() {
        return id;
    }

    public String getGreeting() {
        return greeting;
    }
}

step3 创建一个Controller类

Controller类负责处理客户端的请求,它相当于Struts2的Action,但是它们又有很多不同,如Controller类是基于方法拦截,Struts2的Action是基于类拦截等等。

package hello;
/**
 * 描述:
 *
 * @author halo
 * @create 2018-06-30 13:17
 */
@RestController
public class GreetingController {

    private static final String template= "Hello,%S!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value = "name",defaultValue = "world")String name){
        return new Greeting(counter.incrementAndGet(),String.format(template,name));
    }
}

正如上面所看到的,这个Controller类很简洁,但是它的背后做了很多大量的工作,如利用Spring4.x的新特性@RestController来标注这个类是一个Controller,在这个类里面每一个方法所返回的对象将替代以前的视图对象,相当于之前@Controller和@ResponseBody共同使用的功能;那么你可能会问,它是怎么把Greeting转换成JSON对象的呢?这要归功于 Jackson JSON library,因为它被配置在classpath上,Spring会使用自己的MappingJackson2HttpMessageConverter把它会自动转换回JSON对象。

@RequestMapping('/greeting')默认是GET方法请求,当你的请求是/greeting的形式,那么将会被greeting方法拦截;
@RequestParam(value='',defaultValue=''),绑定URI中的参数值到方法参数中,如果请求携带了参数,它会把参数赋值给方法参数name,否则使用默认值;

step4 Done! Make the application executable

创建一个Application类,包含Main方法。

@SpringBootApplication
public class Application {
    public static void main(String[] args){
        SpringApplication.run(Application.class,args);
    }
}

当你运行这个程序,你会惊讶的发现,并不需要把此项目打成war包然后再放到Tomcat中,也没有任何.xml文件,包括Web.xml文件,就能把程序运行起来并输入http://localhost:8080/greeting看到我们预期的结果。

why?

这完全要归功于Spring boot,它通过一个注解@SpringBootApplication它完成了SpringMVC中 DispatchServlet的配置,完成了Web.xml的配置,当程序运行时会把内置的Tomcat Servlet 启动并把项目部署在里面。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值