您的位置:首页 > 编程语言 > Java开发

Eclipse+Jersey实现RESTful服务

2015-12-08 11:11 513 查看
本人的环境如下:

Eclipse
Jersey-1.19
Tomcat v8.0 Server

方法一:POJO支持

第一步:创建动态Web项目EShopRESTfulWS,依据如下图所示过程操作,最后点击“Finish”。





第二步:右击项目,选择Import菜单,加载jersey中必要的包,最后点击“Finish”。本项目中使用jersey-1.19版本,下载官方地址:https://jersey.java.net/download.html。







第三步:右击WebContent\Web-INF\lib目录下刚导入的Jersey包,选择Import菜单项将包加入搜索路径中。



第四步:创建POJO类——User。

package com.shewo.eshop.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class User {

private String firstName = "";
public String getFirstName(){
return this.firstName;
}

public void setFirstName(String firstName){
this.firstName = firstName;
}

private String lastName = "";
public String getLastName(){
return this.lastName;
}

public void setLastName(String lastName){
this.lastName = lastName;
}

private int age = 0;
public int getAge(){
return this.age;
}

public void setAge(int age){
this.age = age;
}
}

第五步:创建服务实现类——UserService。
package com.shewo.eshop.restws;

import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.Produces;

import com.shewo.eshop.model.*;

@Path("UserService")
public class UserService {

@GET
@Path("/getUser")
@Produces(MediaType.APPLICATION_JSON)
public User getUser() {
User user = new User();
user.setAge(10);
user.setFirstName("Meili");
user.setLastName("Wang");

return user;
}
}


第六步:配置 web.xml文件,添加基于Servlet的部署
<?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>EShopRESTfulWS</display-name>
<servlet>
<servlet-name>User REST Service</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.shewo.eshop.restws</param-value>
</init-param>

<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>User REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>

完成上述步骤后,可以右击项目,选择:RunAs-Run On Server,选择你所安装的HTTPServer,这里我用的是Tomcat v8.0 Server。如下图:



点击“Finish”,运行Tomcat。这里需要注意:在此之前,本机不能有其它Tomcat实例在运行,否则会由于大家默认端口都为8080,从而造成冲突。

Server启动成功后,可以用如下URL测试:http://localhost:8080/EShopRESTfulWS/rest/UserService/getUser

网页中出现如下结果表示系统运行正常:{"age":"10","firstName":"Meili","lastName":"Wang"}

URL说明:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Eclipse Jersey RESTful