Jersey 1.x实现HelloRestful
Jersey RESTful是实现了JAX-RS规范支持JAX-RS API的一套开源、稳定的Java框架,自问世之日起,就因其稳定、高效、便捷的特性被广大开发者所喜爱。经过不断的更新改进,Jeysey目前最新的版本为2.6. 但由于2.X版本与1.X版本相差较大,2.X版本与一些组件在兼容性和配置方面还存在一些问题, 1.X版本仍然是市场上的主力军。因此,Jersey1.X版本的HelloRestful便是本文的主要内容。
运行环境如下:
-
jdk 1.7
-
Tomcat 8
-
Jersey 1.18
-
Eclipse Kepler
实现步骤:
1. 从Jersey官网下载Jersey 1.18版本。
2. 在Eclipse中新建Dynamic Web Project,在工程中输入“HelloRestWorld”。
3. 解压第一步下载下来的Jersey 1.18.zip,将下的jersey-archive-1.18\lib下的jar拷贝到/HelloRestWorld/WebContent/WEB-INF/lib目录下。
4. 新建HelloWorld.java,代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
package com.favccxx.favrestful;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path ( "/hello" )
public class HelloWorld {
@GET
@Produces (MediaType.TEXT_PLAIN)
public String getIt() {
return "Welcome to Jeysey Hello World!" ;
}
} |
5. 修改web.xml,配置Jersey转发。
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
|
<? 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"
id = "WebApp_ID" version = "3.1" >
< display-name >HelloRestWorld</ display-name >
< servlet >
< servlet-name >JerseyRESTService</ servlet-name >
< servlet-class >com.sun.jersey.spi.container.servlet.ServletContainer</ servlet-class >
< init-param >
< param-name >com.sun.jersey.config.property.packages</ param-name >
< param-value >com.favccxx.favrestful</ param-value >
</ init-param >
< load-on-startup >1</ load-on-startup >
</ servlet >
< servlet-mapping >
< servlet-name >JerseyRESTService</ servlet-name >
< url-pattern >/rest/*</ url-pattern >
</ servlet-mapping >
< 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 >
</ web-app >
|
6. 启动Tomcat,在浏览器中输入:http://localhost:8080/HelloRestWorld/rest/hello。
本文转自 genuinecx 51CTO博客,原文链接:http://blog.51cto.com/favccxx/1569417,如需转载请自行联系原作者