目錄
What is JAX-RS?
Setting Up a Basic JAX-RS Project
Creating a Simple REST Resource
Registering Resources and Running the Server
Handling JSON with POJOs
Additional Features
Best Practices
首頁 Java java教程 用JAX-RS在Java建立靜止的API

用JAX-RS在Java建立靜止的API

Aug 06, 2025 am 08:49 AM
java

JAX-RS 是一種用於在Java 中構建RESTful API 的標準化方法,通過註解簡化REST 服務開發。 1. JAX-RS 是Jakarta EE 的規範,需依賴Jersey、RESTEasy 或Apache CXF 等實現;2. 使用@Path、@GET、@POST 等註解將Java 方法映射為HTTP 端點;3. 通過@Produces 和@Consumes 定義數據格式,結合Jackson 等庫實現JSON 序列化;4. 可通過ResourceConfig 註冊資源類並使用嵌入式服務器(如Grizzly)啟動服務;5. 推薦使用POJO/DTO、異常映射、輸入驗證和OpenAPI 文檔等最佳實踐以提升可維護性。 JAX-RS 提供了可靠且廣泛支持的REST 開發方式,適合構建企業級Web 服務。

Building RESTful APIs in Java with JAX-RS

Building RESTful APIs in Java with JAX-RS is a straightforward and standardized way to create web services that follow REST principles. JAX-RS (Java API for RESTful Web Services) is part of Java EE (now Jakarta EE) and provides a set of annotations and interfaces to simplify the development of REST endpoints.

Building RESTful APIs in Java with JAX-RS

What is JAX-RS?

JAX-RS is a specification, not an implementation. It defines how Java classes and methods can be annotated to expose HTTP endpoints. Popular implementations include:

  • Jersey (reference implementation by Eclipse Foundation)
  • RESTEasy (by Red Hat, commonly used with WildFly)
  • Apache CXF

You can use any of these with servlet containers like Tomcat or full Java EE application servers.

Building RESTful APIs in Java with JAX-RS

Setting Up a Basic JAX-RS Project

You can start with Maven or Gradle. Here's a minimal pom.xml snippet using Jersey and embedded Grizzly server:

 <dependencies>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
        <version>3.1.0</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-grizzly2-http</artifactId>
        <version>3.1.0</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.inject</groupId>
        <artifactId>jersey-hk2</artifactId>
        <version>3.1.0</version>
    </dependency>
</dependencies>

Creating a Simple REST Resource

Use annotations to map Java methods to HTTP operations.

Building RESTful APIs in Java with JAX-RS
 import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;

@Path("/users")
public class UserResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String getAllUsers() {
        return "[{\"id\": 1, \"name\": \"Alice\"}, {\"id\": 2, \"name\": \"Bob\"}]";
    }

    @GET
    @Path("/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public String getUserById(@PathParam("id") int id) {
        return String.format("{\"id\": %d, \"name\": \"User%d\"}", id, id);
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public void createUser(String userData) {
        System.out.println("Received: " userData);
    }
}

Key annotations:

  • @Path – defines the URL path segment
  • @GET , @POST , etc. – map to HTTP methods
  • @PathParam , @QueryParam – extract values from URLs
  • @Produces , @Consumes – declare MIME types

Registering Resources and Running the Server

With Jersey and Grizzly, you can bootstrap the server like this:

 import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;

import java.net.URI;

public class Main {
    public static void main(String[] args) {
        ResourceConfig config = new ResourceConfig(UserResource.class);
        URI baseUri = URI.create("http://localhost:8080/api/");
        HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri, config);
        System.out.println("Server running at " baseUri);
        System.in.read(); // Keep server running
        server.shutdown();
    }
}

Now you can access:

  • GET http://localhost:8080/api/users → returns list
  • GET http://localhost:8080/api/users/1 → returns user 1

Handling JSON with POJOs

Instead of raw strings, use POJOs with JSON binding (via Jackson or JSON-B):

 public class User {
    private int id;
    private String name;

    // Constructors, getters, setters
    public User() {}

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    // getters and setters...
}

Update the resource:

 @GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public User getUserById(@PathParam("id") int id) {
    return new User(id, "User" id);
}

Ensure you have a JSON provider in classpath:

 <dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>3.1.0</version>
</dependency>

Additional Features

  • Query Parameters : Use @QueryParam("name") String name
  • Headers : Use @HeaderParam("Authorization") String auth
  • Filters/Interceptors : Add logging, auth, CORS
  • Exception Mapping : Implement ExceptionMapper<t></t> to handle errors gracefully
  • Dependency Injection : Works with HK2 (default in Jersey)

Best Practices

  • Keep resource classes focused (one per domain entity)
  • Return proper HTTP status codes ( Response.status(201).entity(user).build() )
  • Use DTOs instead of exposing internal models
  • Validate input with Bean Validation ( @Valid , @NotNull )
  • Document APIs with OpenAPI/Swagger (via extensions like Swagger-Jersey2)

Basically, JAX-RS gives you a clean, annotation-driven way to build REST APIs in Java. Once you understand the core annotations and choose a solid implementation like Jersey or RESTEasy, it becomes easy to scale and maintain. Not flashy, but reliable and widely supported.

以上是用JAX-RS在Java建立靜止的API的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

Rimworld Odyssey溫度指南和Gravtech
1 個月前 By Jack chen
Rimworld Odyssey如何釣魚
1 個月前 By Jack chen
我可以有兩個支付帳戶嗎?
1 個月前 By 下次还敢
初學者的Rimworld指南:奧德賽
1 個月前 By Jack chen
PHP變量範圍解釋了
3 週前 By 百草

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Laravel 教程
1603
29
PHP教程
1506
276
Edge PDF查看器不起作用 Edge PDF查看器不起作用 Aug 07, 2025 pm 04:36 PM

testthepdfinanotherapptoderineiftheissueiswiththefileoredge.2.enablethebuilt inpdfviewerbyTurningOff“ eflblyopenpenpenpenpenpdffilesexternally”和“ downloadpdffiles” inedgesettings.3.clearbrowsingdatainclorwearbrowsingdataincludingcookiesandcachedcachedfileresteroresoreloresorelorsolesoresolesoresolvereresoreorsolvereresoreolversorelesoresolvererverenn

用Docker將Java應用程序部署到Kubernetes 用Docker將Java應用程序部署到Kubernetes Aug 08, 2025 pm 02:45 PM

容器化Java應用:創建Dockerfile,使用基礎鏡像如eclipse-temurin:17-jre-alpine,複製JAR文件並定義啟動命令,通過dockerbuild構建鏡像並用dockerrun測試本地運行。 2.推送鏡像到容器註冊表:使用dockertag標記鏡像並推送到DockerHub等註冊表,需先登錄dockerlogin。 3.部署到Kubernetes:編寫deployment.yaml定義Deployment,設置副本數、容器鏡像和資源限制,編寫service.yaml創建

如何在Java中實現簡單的TCP客戶端? 如何在Java中實現簡單的TCP客戶端? Aug 08, 2025 pm 03:56 PM

Importjava.ioandjava.net.SocketforI/Oandsocketcommunication.2.CreateaSocketobjecttoconnecttotheserverusinghostnameandport.3.UsePrintWritertosenddataviaoutputstreamandBufferedReadertoreadserverresponsesfrominputstream.4.Usetry-with-resourcestoautomati

VS代碼快捷方式專注於Explorer面板 VS代碼快捷方式專注於Explorer面板 Aug 08, 2025 am 04:00 AM

VSCode中可通過快捷鍵快速切換面板與編輯區。要跳轉至左側資源管理器面板,使用Ctrl Shift E(Windows/Linux)或Cmd Shift E(Mac);返回編輯區可用Ctrl `或Esc或Ctrl 1~9。相比鼠標操作,鍵盤快捷鍵更高效且不打斷編碼節奏。其他技巧包括:Ctrl KCtrl E聚焦搜索框,F2重命名文件,Delete刪除文件,Enter打開文件,方向鍵展開/收起文件夾。

如何使用Mockito在Java中嘲笑? 如何使用Mockito在Java中嘲笑? Aug 07, 2025 am 06:32 AM

要有效使用Mockito進行Java單元測試,首先需添加Mockito依賴,Maven項目在pom.xml中加入mockito-core依賴,Gradle項目添加testImplementation'org.mockito:mockito-core:5.7.0';接著通過@Mock註解(配合@ExtendWith(MockitoExtension.class))或mock()方法創建模擬對象;然後使用when(...).thenReturn(...)等方式對模擬對象的方法行為進行存根,也可配置異

修復:Windows Update無法安裝 修復:Windows Update無法安裝 Aug 08, 2025 pm 04:16 PM

runthewindowsupdatetrubloubleshooterviaSettings>更新&安全> is esseShootsoAtomationfixCommonissues.2.ResetWindowSupDateComponentsByStoppingRealatedServices,RenamingTheSoftWaredWaredWaredSoftwaredSistribution andCatroot2Folders,intrestrestartingthertingthertingtherserviceSteStoceTocle

Java對象的序列化過程是什麼? Java對象的序列化過程是什麼? Aug 08, 2025 pm 04:03 PM

JavaserializationConvertSanObject'SstateIntoAbyTeSteAmForStorageorTransermission,andDeserializationReconstructstheObjectStheObjectFromThstream.1.toenableserialization,aclassMustimustimplementTheSerializableizableface.2.UseObjectObjectObjectObjectOutputputputputputtreamToserialializeanobectizeanobectementeabectenobexpent,savin

如何在Java中使用一個時循環 如何在Java中使用一個時循環 Aug 08, 2025 pm 04:04 PM

AwhileloopinJavarepeatedlyexecutescodeaslongastheconditionistrue;2.Initializeacontrolvariablebeforetheloop;3.Definetheloopconditionusingabooleanexpression;4.Updatethecontrolvariableinsidethelooptopreventinfinitelooping;5.Useexampleslikeprintingnumber

See all articles