在 Jersey 中,你可以通过多种方式从 HTTP 请求中提取参数。以下是一些常见的参数提取方式及其代码示例:
1. 路径参数(Path Parameters)
使用@PathParam
注解从 URL 路径中提取参数。
java
@Path("/users/{id}")
public class UserResource {
@GET
public Response getUser(@PathParam("id") String userId) {
return Response.ok("User ID: " + userId).build();
}
}
2. 查询参数(Query Parameters)
使用@QueryParam
注解从 URL 查询字符串中提取参数。
java
@Path("/users")
public class UserResource {
@GET
public Response getUsers(@QueryParam("name") String name,
@QueryParam("age") int age) {
return Response.ok("Name: " + name + ", Age: " + age).build();
}
}
3. 表单参数(Form Parameters)
使用@FormParam
注解从表单数据中提取参数,通常用于 POST 请求。
java
@Path("/login")
public class AuthResource {
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response login(@FormParam("username") String username,
@FormParam("password") String password) {
return Response.ok("Username: " + username).build();
}
}
4. 头部参数(Header Parameters)
使用@HeaderParam
注解从 HTTP 请求头中提取参数。
java
@Path("/api")
public class ApiResource {
@GET
public Response processRequest(@HeaderParam("User-Agent") String userAgent) {
return Response.ok("User-Agent: " + userAgent).build();
}
}
5. Cookie 参数
使用@CookieParam
注解从 HTTP Cookie 中提取参数。
java
@Path("/session")
public class SessionResource {
@GET
public Response checkSession(@CookieParam("JSESSIONID") String sessionId) {
return Response.ok("Session ID: " + sessionId).build();
}
}
6. 矩阵参数(Matrix Parameters)
使用@MatrixParam
注解从 URL 路径中的矩阵参数部分提取参数。
java
@Path("/products")
public class ProductResource {
@GET
@Path("{category}")
public Response getProducts(@PathParam("category") String category,
@MatrixParam("color") String color) {
return Response.ok("Category: " + category + ", Color: " + color).build();
}
}
7. 上下文参数(Context Parameters)
使用@Context
注解注入 JAX-RS 提供的上下文对象,如UriInfo
、Request
等。
java
@Path("/context")
public class ContextResource {
@GET
public Response getContextInfo(@Context UriInfo uriInfo) {
String path = uriInfo.getAbsolutePath().toString();
return Response.ok("Path: " + path).build();
}
}
8. Bean 参数
使用@BeanParam
注解将多个参数封装到一个 JavaBean 中。
java
public class UserParams {
@PathParam("id") private String id;
@QueryParam("name") private String name;
@HeaderParam("X-Token") private String token;
// getters and setters
}
@Path("/users/{id}")
public class UserResource {
@GET
public Response getUser(@BeanParam UserParams params) {
return Response.ok("ID: " + params.getId() + ", Name: " + params.getName()).build();
}
}
这些是 Jersey 中提取不同类型参数的常见方法。根据你的具体需求,选择合适的注解和方式来提取参数。