标签:jersey web services java eclipse maven
创建一个新项目:
使用maven & Eclipse (Mars)
Maven命令行创建一个新项目(maven环境搭建如不知晓自己查去)
mvn archetype:generate -DarchetypeArtifactId=jersey-quickstart-grizzly2 -DarchetypeGroupId=org.glassfish.jersey.archetypes -DinteractiveMode=false -DgroupId=com.example -DartifactId=simple-service -Dpackage=com.example -DarchetypeVersion=2.14
这要下载一些包 耐心等候……
处理完毕后,你会发现simple-service已经创建
导入到eclipse中,(eclipse要安装maven插件,怎么安装,自己去查)
导入成功后的目录结构如下图
打开包com.example下的Main.java
package com.example; import org.glassfish.grizzly.http.server.HttpServer; import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; import org.glassfish.jersey.server.ResourceConfig; import java.io.IOException; import java.net.URI; /** * Main class. * */ public class Main { // Base URI the Grizzly HTTP server will listen on public static final String BASE_URI = "http://localhost:8080/myapp/"; /** * Starts Grizzly HTTP server exposing JAX-RS resources defined in this application. * @return Grizzly HTTP server. */ public static HttpServer startServer() { // create a resource config that scans for JAX-RS resources and providers // in com.example package final ResourceConfig rc = new ResourceConfig().packages("com.example"); // create and start a new instance of grizzly http server // exposing the Jersey application at BASE_URI return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc); } /** * Main method. * @param args * @throws IOException */ public static void main(String[] args) throws IOException { final HttpServer server = startServer(); System.out.println(String.format("Jersey app started with WADL available at " + "%sapplication.wadl\nHit enter to stop it...", BASE_URI)); System.in.read(); server.stop(); } }
运行之后,控制台输出如下信息:
按照提示我们在浏览器输入http://localhost:8080/myapp/application.wadl,奇迹出现了,如下图所示(⊙o⊙)…
下一个提示出现了 http://localhost:8080/myapp/myresource,返回了一串文本信息。如下图
为什么会是这个访问路径,又为什么返回Got it ! 到底是怎么回事呢。我啥都不知道啊!
com.example还有个文件,MyResource.java,打开看看。
package com.example; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; /** * Root resource (exposed at "myresource" path) */ @Path("myresource") public class MyResource { /** * Method handling HTTP GET requests. The returned object will be sent * to the client as "text/plain" media type. * * @return String that will be returned as a text/plain response. */ @GET @Produces(MediaType.TEXT_PLAIN) public String getIt() { return "Got it!"; } }貌似跟这有点联系,到底是怎么回事呢,下回再议啊……
命令行那句话,Hit enter to stop it... OK,stop it.
mission completed!
O(∩_∩)O~
JAVA RESTful Web Services - Jersey 入门
标签:jersey web services java eclipse maven
原文地址:http://blog.csdn.net/microlmj/article/details/42551497