随着服务器的处理能力越来越强,业务需求量的不断累积,越来越多的公司开始从单一服务器,单一业务承载变成了多服务器,多业务承载的快速扩展的过程中。传统的方法很难满足和应付这种业务量的增长和部署方式的改变。所以RESTful service作为一种分布式服务的最佳实践,应运而生。
说到RESTful Service,我们这里首先来明白一下他的基本概念:它是用于创建分布式超文本媒体的一种架构方式,我们可以通过标准的HTTP(GET,POST,PUT,DELETE)操作来构建基于面向资源的软件架构方式(Resource-Oriented Architecture (ROA))。它是独立于任何技术或者平台的,所以人们经常将符合这种操作规范的服务称为“RESTful services”。说白了,就是通过标准的HTTP操作,通过规定的访问路径,来获取资源的一种方式。RESTful Service在不同的编程平台中,有不同的编程接口提供支持。比如说在.NET中,可以通过WCF或者是WebAPI来创建标准的REST fulservice。而在JAVA中,可以通过JAX-RS和Jersey来创建这种RESTful Service。那么说道这里,JAX-RS和Jersey都是什么东东呢?
JAX-RS:专门为RESTful Service提供的Java API接口,属于Java EE6的一部分。我们可以用这些丰富的接口来实现自己想要的RESTful风格的分布式服务。
Jersey:属于开源软件,是对JAX-RS(JSR 311)的扩展,它提供了更加丰富的API接口,可以让开发者创建RESTful服务更加的方便。
下面我们将开始我们的创建之旅。
步骤一:
在STS中,依次点击 File->New-> Dynamic Web Project 来创建一个MyRESTfulServiceDaemon的项目:
创建完毕以后,点击Finish按钮。
步骤二:
然后当项目加载以后,去\WebContent\WEB-INF\路径下面检查是否有web.xml文件,如果没有的话,你需要在当前项目上右击,然后选择Java EE Tools –> Generate Deployment Descriptor Stub , 点击完毕后,你会发现web.xml文件已经被生成了:
步骤三:
现在,在项目上右击,依次点击Configure -> Convert to Maven Project将项目转变成Maven Project。在弹出的Create new POM对话框中,我们填写上相关的信息,然后确定即可:
步骤四:
打开pom.xml文件,添加如下的依赖项,他们分别是: asm.jar, jersey-bundle.jar, json.jar, jersey-server.jar, jersey-core.jar。
这些包你可以通过编辑pom.xml进行手动添加,也可以通过对话框自动添加,这里我们采用自动添加方式。双击pom.xml,然后切换到Dependencies选项卡,分别将上述的包进行添加:
添加完毕以后界面是这样的:
pom.xml文件的内容是这样的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | < 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 >MyRESTfulServiceDaemon</ groupId > < artifactId >MyRESTfulServiceDaemon</ artifactId > < version >0.0.1-SNAPSHOT</ version > < packaging >war</ packaging > < build > < sourceDirectory >src</ sourceDirectory > < plugins > < plugin > < artifactId >maven-compiler-plugin</ artifactId > < version >3.3</ version > < configuration > < source >1.8</ source > < target >1.8</ target > </ configuration > </ plugin > < plugin > < artifactId >maven-war-plugin</ artifactId > < version >2.6</ version > < configuration > < warSourceDirectory >WebContent</ warSourceDirectory > < failOnMissingWebXml >false</ failOnMissingWebXml > </ configuration > </ plugin > </ plugins > </ build > < dependencies > < dependency > < groupId >org.json</ groupId > < artifactId >json</ artifactId > < version >20140107</ version > </ dependency > < dependency > < groupId >com.sun.jersey</ groupId > < artifactId >jersey-server</ artifactId > < version >1.19</ version > </ dependency > < dependency > < groupId >com.sun.jersey</ groupId > < artifactId >jersey-core</ artifactId > < version >1.19</ version > </ dependency > < dependency > < groupId >asm</ groupId > < artifactId >asm</ artifactId > < version >3.3.1</ version > </ dependency > < dependency > < groupId >com.sun.jersey</ groupId > < artifactId >jersey-bundle</ artifactId > < version >1.19</ version > </ dependency > </ dependencies > </ project > |
步骤五:
配置好pom.xml,就意味着maven这块暂时配置完毕,到时候运行 maven install命令,就可以将这些包自动下载到本地来。
现在,我们打开web.xml,然后按照下面xml示例,将不存在的servlet节点和servlet-mapping节点拷贝过去:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <? xml version="1.0" encoding="UTF-8"?> < web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> < display-name >MyRESTfulServiceDaemon</ display-name > < welcome-file-list > < welcome-file >index.html</ welcome-file > < welcome-file >index.htm</ welcome-file > < welcome-file >index.jsp</ welcome-file > < welcome-file >default.html</ welcome-file > < welcome-file >default.htm</ welcome-file > < welcome-file >default.jsp</ welcome-file > </ welcome-file-list > < servlet > < servlet-name >Jersey Web Application</ servlet-name > < servlet-class >com.sun.jersey.spi.container.servlet.ServletContainer</ servlet-class > < load-on-startup >1</ load-on-startup > </ servlet > < servlet-mapping > < servlet-name >Jersey Web Application</ servlet-name > < url-pattern >/api/*</ url-pattern > </ servlet-mapping > </ web-app > |
步骤六:
配置完毕后,我们现在来编码,在Java Resources/src/目录下创建一个MyService.java的类,然后输入如下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; @Path ( "/myservice" ) public class MyService { @GET @Produces ( "application/xml" ) public String convertCtoF() { Double fahrenheit; Double celsius = 36.8 ; fahrenheit = ((celsius * 9 ) / 5 ) + 32 ; String result = "@Produces(\"application/xml\") Output: \n\nC to F Converter Output: \n\n" + fahrenheit; return "<ctofservice>" + "<celsius>" + celsius + "</celsius>" + "<ctofoutput>" + result + "</ctofoutput>" + "</ctofservice>" ; } @Path ( "{c}" ) @GET @Produces ( "application/xml" ) public String convertCtoFfromInput( @PathParam ( "c" ) Double c) { Double fahrenheit; Double celsius = c; fahrenheit = ((celsius * 9 ) / 5 ) + 32 ; String result = "@Produces(\"application/xml\") Output: \n\nC to F Converter Output: \n\n" + fahrenheit; return "<ctofservice>" + "<celsius>" + celsius + "</celsius>" + "<ctofoutput>" + result + "</ctofoutput>" + "</ctofservice>" ; } } |
输入完毕后,再创建一个 MyServicex.java的类,输入如下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import org.json.JSONException; import org.json.JSONObject; @Path ( "/myservicex" ) public class MyServicex { @GET @Produces ( "application/json" ) public Response convertFtoC() throws JSONException { JSONObject jsonObject = new JSONObject(); Double fahrenheit = 98.24 ; Double celsius; celsius = (fahrenheit - 32 )* 5 / 9 ; jsonObject.put( "F Value" , fahrenheit); jsonObject.put( "C Value" , celsius); String result = "@Produces(\"application/json\") Output: \n\nF to C Converter Output: \n\n" + jsonObject; return Response.status( 200 ).entity(result).build(); } @Path ( "{f}" ) @GET @Produces ( "application/json" ) public Response convertFtoCfromInput( @PathParam ( "f" ) float f) throws JSONException { JSONObject jsonObject = new JSONObject(); float celsius; celsius = (f - 32 )* 5 / 9 ; jsonObject.put( "F Value" , f); jsonObject.put( "C Value" , celsius); String result = "@Produces(\"application/json\") Output: \n\nF to C Converter Output: \n\n" + jsonObject; return Response.status( 200 ).entity(result).build(); } } |
代码编写完毕后,我们会看到很多错误,是因为jar包都还没下载下来。依次运行如下两个命令:
1 2 3 | 右击项目->Maven->Update Project. 右击项目->Run As->Maven Build |
命令运行完毕后,我们就可以看到代码没有错误提示了。同时在日志信息里面,你可以看到我们的项目build成功了。
步骤七:
现在来开始运行我们的项目,在项目上右击,然后选择Run As->Run On Server,在弹出的对话框中,点击Finish按钮即可打开网址http://localhost:8080/MyRESTfulServiceDaemon/,但是页面会显示404错误,是因为我们如果想调用页面,需要按照如下的方式输入:
访问myservice页面:
http://localhost:8080/MyRESTfulServiceDaemon/api/myservice,我们看到的结果如下:
然后我们为其输入参数http://localhost:8080/MyRESTfulServiceDaemon/api/myservice/35,可以看到内容的更改:
最后我们测试myservicex:http://localhost:8080/MyRESTfulServiceDaemon/api/myservicex/35,可以看到提示下载json文件的命令,说明我们的json数据请求也是成功的:
完结:
到这里,我们的示例就完结了,是不是很简单呢? 不得不说maven确实挺好用的。需要更多的参考知识,大家可以移步到下面的链接去寻找。
How to build RESTful Service with Java using JAX-RS and Jersey (Example)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!