package com.itheima.controller;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/person")
public class PersonResource {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String get(){
return "GET Person resource";
}
}
package com.itheima.config;
import com.itheima.controller.PersonResource;
import org.glassfish.jersey.server.ResourceConfig;
//配置类,配置这个项目有什么资源
public class ApiResourceConfig extends ResourceConfig {
public ApiResourceConfig() {
register(PersonResource.class);
}
}
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>jerseyServletservlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainerservlet-class>
<init-param>
<param-name>javax.ws.rs.Applicationparam-name>
<param-value>com.itheima.config.ApiResourceConfigparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>jerseyServletservlet-name>
<url-pattern>/*url-pattern>
servlet-mapping>
web-app>
@Path("/person")
public class PersonResource {
@GET
@Path("{id}")
@Produces(MediaType.TEXT_PLAIN)
public String get(@PathParam("id") Long id){
return "GET Person resource"+id;
}
}
不仅支持路径参数,还支持表达式
@Path("/person")
public class PersonResource {
@GET
@Path("/{username: [a-zA-Z]{5,8}}")//支持正则表达式:大小写字母并且5到8个字符之间
@Produces(MediaType.TEXT_PLAIN)
public String getUser(@PathParam("username") String username){
return "GET Person resource"+username;
}
}
@Path("/person")
//@Produces(MediaType.TEXT_PLAIN)
public class PersonResource {
@GET
@Path("/text")
@Produces({"text/plain","text/html"})
public String getTextOrHtml(){
return "hello";
}
}
设置Accept为text/plain或text/html
@Path("/person")
//@Produces(MediaType.TEXT_PLAIN)
public class PersonResource {
@GET
@Path("/text")
//服务端指定,text/plain 品质因数为0.9
@Produces({"text/plain; qs=0.9","text/html"})
public String getTextOrHtml(){
return "hello";
}
}
访问,没有制定请求头Accept,响应头是text/html
用来获取url请求路径中的参数(前面已经使用过)
@Path("/person")
//@Produces(MediaType.TEXT_PLAIN)
public class PersonResource {
// 请求路径中带?name=xxx&age=18
@GET
@Produces("text/plain")
public String get(@QueryParam("name") String name,@QueryParam("age") Integer age){
return name+age;
}
}
如果不传入值,也能匹配到,如果不加@DefaultValue,则包装类返回null,加入@DefaultValue之后,返回指定的内容
@Path("/person")
//@Produces(MediaType.TEXT_PLAIN)
public class PersonResource {
// 请求路径中带?name=xxx&age=18
@GET
@Produces("text/plain")
public String get(@DefaultValue("yyds")@QueryParam("name") String name,@DefaultValue("yyds")@QueryParam("age") Integer age){
return name+age;
}
}
public class PersonResource {
// 请求路径中带?ids=1&ids=2
// @QueryParam就是活的路径中?后面的内容,比如localhost:8080/person?ids=1&ids=2
// 需要一个集合来接收多个数据,@QueryParam("ids")中的ids与路径中的ids是一致的
@DELETE
public void get(@QueryParam("ids") List<Long> ids){
System.out.println(ids);
}
}
Postman:
路径参数是以;分号开头
请求路径localhost:8080/person;id=1010;name=张三,李四
@Path("/person")
//@Produces(MediaType.TEXT_PLAIN)
public class PersonResource {
// 矩阵参数 @MatrixParam
@GET
public String get(@MatrixParam("id") Integer id,@MatrixParam("name") List<String> names){
System.out.println(id);
System.out.println(names);
return "ok";
}
}
postman:
@Path("/person")
//@Produces(MediaType.TEXT_PLAIN)
public class PersonResource {
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)//传过来的是表单类型的数据
public String get(@FormParam("name") String name,@FormParam("age") Integer age){
return name+age;
}
}
@Path("/person")
//@Produces(MediaType.TEXT_PLAIN)
public class PersonResource {
// 获取请求头和cookie中的值
@GET
public String get(@HeaderParam("User-Agent") String head,
@HeaderParam("Cookie") String cookie,
@CookieParam("name") String name){
System.out.println(head);
System.out.println(cookie);
System.out.println(name);
return head+";"+cookie+";"+name;
}
}
@CookieParam专门获得请求头中的值
发送一个POST请求,携带的数据是form类型的
一个一个定义@FormParam太麻烦了,所以用到了@BeanParam注解,将form中的key封装为一个domain类
Person.java
package com.itheima.domain;
import lombok.Data;
import javax.ws.rs.FormParam;
@Data //包括了get、set方法和tostring
public class Person {
@FormParam("id")
private Long id;
@FormParam("name")
private String name;
@FormParam("age")
private Integer age;
}
因为传的是表单类型的参数,所以实体类中的属性要加@FormParam
postman:
@Path("/person")
//@Produces(MediaType.TEXT_PLAIN)
public class PersonResource {
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void save(@BeanParam Person person){
System.out.println(person);
}
}
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.0.1version>
<scope>providedscope>
dependency>
@Path("/person")
//@Produces(MediaType.TEXT_PLAIN)
public class PersonResource {
@Context
ServletContext servletContext;
@GET
public void HttpInfo(@Context HttpServletRequest request, @Context HttpServletResponse response){
System.out.println(this);
System.out.println(servletContext);
System.out.println(request);
System.out.println(response);
}
}
默认注解@RequestScoped,this都不一样
加上@Singleton
<dependency>
<groupId>org.glassfish.jersey.mediagroupId>
<artifactId>jersey-media-json-jacksonartifactId>
<version>2.23.2version>
dependency>
@Path("/person")
@Singleton //性能会更好
//@Produces(MediaType.TEXT_PLAIN)
public class PersonResource {
// 返回json格式数据
@GET
@Produces(MediaType.APPLICATION_JSON)
public Person getJson(){
Person person = new Person();
person.setId(1001L);
person.setName("小时光");
person.setAge(12);
return person;
}
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void getSJson2(Person person){
System.out.println(person);
}
目录结构
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.7.13version>
<relativePath/>
parent>
<groupId>com.itheimagroupId>
<artifactId>jersey-springbootartifactId>
<version>0.0.1-SNAPSHOTversion>
<name>jersey-springbootname>
<description>jersey-springbootdescription>
<properties>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jerseyartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
project>
package com.itheima.config;
import com.itheima.web.PersonResource;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
register(PersonResource.class);
}
}
web/PersonResource
package com.itheima.web;
import org.springframework.stereotype.Component;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/person")
@Component
public class PersonResource {
@Path("hello")
@GET
@Produces(MediaType.TEXT_PLAIN)
public String getPerson(){
return "hello";
}
}
postman
@Path("/person")
@Component
public class PersonResource {
@Path("{id}")
@GET
@Produces(MediaType.TEXT_PLAIN)
public String getPerson(@PathParam("id") Integer id){
System.out.println(id);
return "hello";
}
}
pom.xml新增
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.22version>
<scope>providedscope>
dependency>
package com.itheima.web;
import com.itheima.domain.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/person")
@Component
public class PersonResource {
@Autowired
private ApplicationContext ctx;
// 请求方式GET
// 路径 /person/id值
// 状态 200
// 响应数据类型 application/json
// 响应体中的数据就是person
//响应状态 Response类,提供方法设置状态,响应头,响应数据
//根据id去查询数据
@Path("/{id}")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getPerson(@PathParam("id") Integer id){
System.out.println(id);
//下面这段数据,实际情况下是从数据库中获取的
Person person = new Person();
person.setId(1001);
person.setName("xiaoshiguang");
person.setAge(22);
return Response.ok(person)// 不仅设置响应码为200,而且返回json格式的数据
.build();//建立Response对象
}
}
Person.java实体类
package com.itheima.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.ws.rs.FormParam;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
private Integer id;
private String name;
private Integer age;
}
Postman:
package com.itheima.web;
import com.itheima.domain.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Path("/person")
@Component
public class PersonResource {
// 2、做分页查询
// 请求方式GER
// 路径 /person
// 状态 200
// 响应数据类型application/json
// 响应体中的数据是多条person数据
// 还需要返回一共有多少条数据,通过响应头来设置:X-Total-Count
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response page(){
List<Person> personList = new ArrayList<>();
Person p1 = new Person(1001,"p1",18);
Person p2 = new Person(1002,"p2",19);
Person p3 = new Person(1003,"p3",20);
personList = Arrays.asList(p1, p2, p3);
return Response.ok(personList) //SpringBoot下自动转换为json格式的数据
.header("X-Total-Count",personList.size())
.build(); // 创建对象
}
}
注解:@AllArgsConstructor自动生成有参构造器和@NoArgsConstructos无参构造器
package com.itheima.web;
import com.itheima.domain.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Path("/person")
@Component
public class PersonResource {
// 按restful风格
// 3、保存数据
// 发POST请求
// 请求路径 /person/save
// 请求参数是json类型,在请求体中
// 状态 201
// 响应数据类型 application/json
// 响应体中的数据包含被创建的person数据
// 响应头 location:http://localhost:8080/person/id值
@Path("/save")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response save(Person person,@Context UriInfo uriInfo){
// 把person对象存到数据库中
// 避免写死代码
URI uri = uriInfo.getAbsolutePathBuilder()
.path(person.getId() + "")
.build();
System.out.println(uri);
return Response.created(uri) //设置状态码201,并设置响应头location
.entity(person)
.build();
}
}
添加数据
返回结果:
package com.itheima.web;
import com.itheima.domain.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Path("/person")
@Component
public class PersonResource {
// 按restful风格
// 4、修改数据
// 请求类型为POST
// 请求路径为/person/update
// 请求参数为json类型
// 状态码 204
// 没有响应数据
@Path("/update")
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public Response update(Person person){
// 把person对象修改到数据库中
System.out.println(person);
return Response.noContent() //设置响应码为204,并且没有响应数据
.build();
}
}
package com.itheima.web;
import com.itheima.domain.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Path("/person")
@Component
public class PersonResource {
// 按restful风格
// 5、删除数据
// 请求类型为DELETE
// 请求路径为/person/id值
// 状态码为204 没有响应数据
@Path("delete/{id}")
@DELETE
public Response delete(@PathParam("id") Integer id){
// 从数据库中删除该id对应的字段
System.out.println("删除id为:"+id);
return Response.noContent().build();
}
}