通知短信+运营短信,5秒速达,支持群发助手一键发送🚀高效触达和通知客户 广告
# 用Jersey构建RESTful服务1--HelloWorld ## 一、环境 1. Eclipse Juno R2 2. Tomcat 7 3. Jersey 2.x(最新2.11版本测试通过) 下载地址( [https://jersey.java.net/download.html](https://jersey.java.net/download.html)) ## 二、流程 1. Eclipse 中创建一个 Dynamic Web Project ,本例为“RestDemo” 2. 按个各人习惯建好包,本例为“com.waylau.rest.resources” ![](https://box.kancloud.cn/2016-05-11_57332e7543eaa.jpg) 3. 解压jaxrs-ri-2.7,将api、ext、lib文件夹下的jar包都放到项目的lib下; ![](https://box.kancloud.cn/2016-05-11_57332e755c40d.jpg) 项目引入jar包 ![](https://box.kancloud.cn/2016-05-11_57332e7570e69.jpg) 4. 在resources包下建一个class“HelloResource” ``` package com.waylau.rest.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.PathParam; import javax.ws.rs.core.MediaType; @Path("/hello") public class HelloResource { @GET @Produces(MediaType.TEXT_PLAIN) public String sayHello() { return "Hello World!" ; } @GET @Path("/{param}") @Produces("text/plain;charset=UTF-8") public String sayHelloToUTF8(@PathParam("param") String username) { return "Hello " + username; } } ``` 5. 修改web.xml,添加基于Servlet-的部署 ``` <servlet> <servlet-name>Way REST Service</servlet-name> <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> <init-param> <param-name>jersey.config.server.provider.packages</param-name> <param-value>com.waylau.rest.resources</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Way REST Service</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> ``` 6. 项目部署到tomcat,运行 7. 浏览器输入要访问的uri地址 [http://localhost:8089/RestDemo/rest/hello](http://localhost:8089/RestDemo/rest/hello),输出Hello World! ![](https://box.kancloud.cn/2016-05-11_57332e758c880.jpg) [http://localhost:8089/RestDemo/rest/hello/Way%E4%BD%A0%E5%A5%BD%E5%90%97](http://localhost:8089/RestDemo/rest/hello/Way%E4%BD%A0%E5%A5%BD%E5%90%97),输出Hello Way你好吗 ![](https://box.kancloud.cn/2016-05-11_57332e75a3ce1.jpg) 参考:[https://jersey.java.net/documentation/latest/user-guide.html](https://jersey.java.net/documentation/latest/user-guide.html) **本章源码**:[https://github.com/waylau/RestDemo/tree/master/jersey-demo1-helloworld](https://github.com/waylau/RestDemo/tree/master/jersey-demo1-helloworld)