一、入门
controller
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.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>jerseyServlet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.itheima.config.ApiResourceConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jerseyServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
二、注解
1、@Path
@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;
}
}
2、请求方式的注解
3、@Produces
@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
4、@Consumes