ZetCode

JAX-RS @Context

最后修改于 2023 年 1 月 10 日

JAX-RS @Context 教程展示了如何在 Jersey 框架的 RESTful Java Web 应用中使用 @Context 注解。

Jersey

Jersey 是一个用于在 Java 中开发 RESTful Web 服务的框架。它是 Java API for RESTful Web Services (JAX-RS) 规范的参考实现。另一个流行的 JAX-RS 实现是 JBoss 的 RESTEasy。

JAX-RS @Context

JAX-RS @Context 注解允许将与上下文相关的信息注入到类字段、Bean 属性或方法参数中。

JAX-RS @Context 示例

下面的示例是一个简单的 RESTful 应用,它将一些与上下文相关的数据以纯文本形式返回给客户端。

├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── zetcode
    │   │           ├── conf
    │   │           │   └── ApplicationConfig.java
    │   │           └── ws
    │   │               └── MyResource.java
    │   ├── resources
    │   └── webapp
    │       └── META-INF
    │           └── context.xml
    └── test
        └── java

这是项目结构。

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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 
http://maven.apache.org/xsd/maven-4.0.0.xsd">
    
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zetcode</groupId>
    <artifactId>JerseyContext</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>JerseyContext</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    
    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>2.25</version>
        </dependency>
        
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>2.25</version>
        </dependency>
        
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.0</version>
            <scope>provided</scope>
        </dependency>        
        
    </dependencies>

    <build>
        <plugins>
            
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>

        </plugins>
    </build>

</project>

这是 Maven POM 文件。它包含 jersey-container-servletjersey-serverjavax.servlet 依赖项。

context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/JerseyContext"/>

在 Tomcat 的 context.xml 配置文件中,我们定义了应用的上下文路径。

ApplicationConfig.java
package com.zetcode.conf;

import com.zetcode.ws.HelloResource;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("rest")
public class ApplicationConfig extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> set = new HashSet<>();
        set.add(MyResource.class);
        return set;
    }
}

这是应用程序配置类。自从 Servlet 3.0 以来,就可以在没有 web.xml 文件的情况下部署应用程序。Application 定义了 JAX-RS 应用程序的组件并提供其他元数据。在这里,我们注册应用程序所需的资源类、提供程序或属性。

@ApplicationPath("rest")

使用 @ApplicationPath 注解,我们设置了 RESTful Web 服务的路径。

@Override
public Set<Class<?>> getClasses() {
    Set<Class<?>> set = new HashSet<>();
    set.add(MyResource.class);
    return set;
}

getClasses 方法中,我们添加了资源类。在我们的例子中,我们有一个 MyResource 类。

MyResource.java
package com.zetcode.ws;

import javax.inject.Inject;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

@Path("myresource")
public class MyResource {
    
    @Context
    private UriInfo info;
    
    @Context
    private HttpServletRequest servletRequest;    
    
    @Context 
    private ServletContext servletContext;

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public Response message() {

        StringBuilder builder = new StringBuilder();
        
        String baseUri = info.getBaseUri().toASCIIString();
        String method = servletRequest.getMethod();
        String serverInfo = servletContext.getServerInfo();
        
        builder.append("Base uri: ").append(baseUri)
                .append("; HTTP method: ").append(method)
                .append("; Server info: ").append(serverInfo);
        
        String output = builder.toString();
        
        return Response.status(200).entity(output).build();
    }
}

这是 MyResource 类。

@Path("myresource")
public class MyResource {

@Path 指定资源响应的 URL。

@Context
private UriInfo info;

@Context
private HttpServletRequest servletRequest;    

@Context 
private ServletContext servletContext;

在这里,我们使用 @ContextUriInfoHttpServletRequestServletContext 注入到类字段中。

@GET
@Produces(MediaType.TEXT_PLAIN)
public Response message() {

@GET 注解表示带注解的方法响应 HTTP GET 请求。使用 @Produces 注解,我们定义该方法生成纯文本。

StringBuilder builder = new StringBuilder();

String baseUri = info.getBaseUri().toASCIIString();
String method = servletRequest.getMethod();
String serverInfo = servletContext.getServerInfo();

builder.append("Base uri: ").append(baseUri)
        .append("; HTTP method: ").append(method)
        .append("; Server info: ").append(serverInfo);

String output = builder.toString();

从注入的类中,我们获取了基础 URI、HTTP 方法和服务器信息。我们根据收集到的信息构建了一个输出。

return Response.status(200).entity(output).build();

我们将包含信息的响应发送给客户端。

$ curl localhost:8084/JerseyContext/rest/myresource
Base uri: https://:8084/JerseyContext/rest/; HTTP method: GET; 
Server info: Apache Tomcat/8.0.27

在 Tomcat 上部署应用程序后,我们使用 curl 向应用程序发送 GET 请求。

在本教程中,我们使用了 JAX-RS @Context 注解。