一、前言

RESTful API已经成为现代web应用开发中的重要组成部分,使得我们可以通过HTTP请求来访问服务器中的资源。REST是一种基于HTTP协议的软件架构风格,它是面向资源的,RESTful API是符合REST架构风格的API,它是通过HTTP协议访问Web资源的标准化方法。jersey使用了JAX-RS规范来约束API的开发,是基于RESTful风格的框架。


二、SpringBoot集成

1.添加依赖

<!--jersey-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jersey</artifactId>
        </dependency>

2.编写配置类

package com.example.nettydemo.config;

import com.example.nettydemo.controller.JerseyHttp;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.context.annotation.Configuration;

/**
 * @author qx
 * @date 2023/12/28
 * @des Jersey配置
 */
@Configuration
public class JerseyConfig extends ResourceConfig {

    public JerseyConfig() {
        register(JerseyHttp.class);
    }
}

3.编写请求资源类

package com.example.nettydemo.controller;

import com.example.nettydemo.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;

/**
 * @author qx
 * @date 2023/12/28
 * @des 请求资源类
 */
@Path("/hello")
@Component
@Slf4j
public class JerseyHttp {

    @GET
    public String test() {
        return "hello world";
    }

    @GET
    @Path("/{id}")
    public String show(@PathParam("id") Long id) {
        return "返回的数据:" + id;
    }

    @POST
    @Path("/add")
    @Consumes(MediaType.APPLICATION_JSON)
    public User addUser(User user) {
        log.info("user:{}", user);
        return user;
    }


}

4.测试Jersey

启动程序,使用Jersey请求资源类请求数据。

SpringBoot集成Jersey实现RESTful API调用_jersey

SpringBoot集成Jersey实现RESTful API调用_SpringBoot_02

使用postman测试post数据。

SpringBoot集成Jersey实现RESTful API调用_SpringBoot_03

控制台日志:

2023-12-28 11:41:24.044  INFO 920 --- [nio-8090-exec-2] c.e.nettydemo.controller.JerseyHttp      : user:User(id=1, name=admin, age=20)