用JAX-RS在Java建立靜止的API
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 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.

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.

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.

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中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

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

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

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

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

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

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

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

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

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

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

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

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