RESTFUR Web服务JAXRS CRUD示例使用泽西岛
之前,我们已经看到了简单的RESTful Web服务(JAXW),它将JSON返回为响应。
在本教程中,我们将使用将提供CRUD(创建,阅读,更新并删除)操作示例。
我们将使用以下注释进行Crud操作。
| 方法 | 描述 |
|---|---|
| Get | 它用于读取资源 |
| Post | 它用于创建新资源。不是Idempotent方法 |
| Put | 它通常用于更新资源。它是idempotent方法 |
| Delete | 它用于删除资源 |
idempotent意味着多个成功请求的结果不会在初始应用程序之后更改资源状态:删除是幂等的方法,因为当第一次使用删除时,它将删除资源(初始应用程序),但之后,所有其他请求都没有结果,因为资源已被删除。
POST不是IDEMPOTENT方法,因为当我们使用POST创建资源时,它将继续为每个新请求创建资源,因此多个成功请求的结果将不相同。
以下是使用jersey创建简单的RESFFUR Web服务(JAXW)的步骤,该播放器将提供CRUD WHENERION。
1)使用名为"Jaxrsjsoncrudexample"的Eclipse中的Maven创建动态Web项目
Maven依赖项
2)我们需要在类路径中添加泽西jar utility。
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>${jersey.version}</version>
</dependency>
jersey内部使用Hymanson 的JSON处理,因此它将用于将Pojo对象定为JSON。
现在创建pom.xml如下:pom.xml
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.igi.theitroad</groupId>
<artifactId>JAXRSJsonExample</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>JAXRSJsonExample Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<jersey.version>1.18.3</jersey.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>JAXRSJsonExample</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
应用程序配置:
3)创建Web.xml如下所示:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>Archetype Created Web Application</display-name> <servlet> <servlet-name>jersey-serlvet</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>org.igi.theitroad.controller</param-value> </init-param> <init-param> <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name> <param-value>true</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>jersey-serlvet</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> </web-app>
如果我们不使用相同的包,请更改initparam"com.sun.packey.config.property.package"属性以提供正确的控制器包名称。
创建bean类
4)在org.igi.theitroad.Bean中创建Bean名称"country.java"。
package org.igi.theitroad.bean;
public class Country{
int id;
String countryName;
long population;
public Country() {
super();
}
public Country(int i, String countryName,long population) {
super();
this.id = i;
this.countryName = countryName;
this.population=population;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public long getPopulation() {
return population;
}
public void setPopulation(long population) {
this.population = population;
}
}
创建控制器
5)在包org.igi.theitroad.Controller中创建名为"countrycontroller.java"的控制器
package org.igi.theitroad.controller;
import java.util.List;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.igi.theitroad.bean.Country;
import org.igi.theitroad.service.CountryService;
@Path("/countries")
public class CountryController {
CountryService countryService=new CountryService();
@GET
@Produces(MediaType.APPLICATION_JSON)
public List getCountries()
{
List listOfCountries=countryService.getAllCountries();
return listOfCountries;
}
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Country getCountryById(@PathParam("id") int id)
{
return countryService.getCountry(id);
}
@POST
@Produces(MediaType.APPLICATION_JSON)
public Country addCountry(Country country)
{
return countryService.addCountry(country);
}
@PUT
@Produces(MediaType.APPLICATION_JSON)
public Country updateCountry(Country country)
{
return countryService.updateCountry(country);
}
@DELETE
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public void deleteCountry(@PathParam("id") int id)
{
countryService.deleteCountry(id);
}
}
@path(/your_path_at_class_level):将路径设置为基本URL +/your_path_at_class_Level。
基本URL基于应用程序名称,servlet和web.xml"配置文件的URL模式。
@path(/your_path_at_method_level):将路径设置为base url +/your_path_at_class_level +/your_path_at_method_level
@Produces(Mediatype.application_json [,more-types]):@produces定义了用@get注释的方法传递的mime类型。
在示例文本中,生成"文本/JSON")。
创建服务类
6)在package org.igi.theitroad.onitoad.service中创建一个countryservice.java .service它只是一个辅助类,应该由数据库实现替换。
写类不是很好的,它只是用于演示。
package org.igi.theitroad.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.igi.theitroad.bean.Country;
/*
* It is just a helper class which should be replaced by database implementation.
* It is not very well written class, it is just used for demonstration.
*/
public class CountryService {
static HashMap<Integer,Country> countryIdMap=getCountryIdMap();
public CountryService() {
super();
if(countryIdMap==null)
{
countryIdMap=new HashMap<Integer,Country>();
//Creating some objects of Country while initializing
Country NetherlandsCountry=new Country(1, "Netherlands",10000);
Country chinaCountry=new Country(4, "China",20000);
Country nepalCountry=new Country(3, "Nepal",8000);
Country bhutanCountry=new Country(2, "Bhutan",7000);
countryIdMap.put(1,NetherlandsCountry);
countryIdMap.put(4,chinaCountry);
countryIdMap.put(3,nepalCountry);
countryIdMap.put(2,bhutanCountry);
}
}
public List getAllCountries()
{
List countries = new ArrayList(countryIdMap.values());
return countries;
}
public Country getCountry(int id)
{
Country country= countryIdMap.get(id);
return country;
}
public Country addCountry(Country country)
{
country.setId(countryIdMap.size()+1);
countryIdMap.put(country.getId(), country);
return country;
}
public Country updateCountry(Country country)
{
if(country.getId()<=0)
return null;
countryIdMap.put(country.getId(), country);
return country;
}
public void deleteCountry(int id)
{
countryIdMap.remove(id);
}
public static HashMap<Integer, Country> getCountryIdMap() {
return countryIdMap;
}
}
7)这是时候做Maven建造了。
右键单击项目 - >运行AS - > Maven Build
8)将目标作为清洁安装(下面给出),然后单击运行
运行应用程序
9)右键单击项目 - >在服务器上运行AS - >运行
选择Apache Tomcat,然后单击"完成"
10)我们将在邮递员,基于UI的客户端测试此应用程序,用于测试RESTful Web应用程序。
它是Chrome插件。
发射邮递员。
如果我们想要基于Java的客户端,那么我们还可以使用如何在Java中发送或者发布请求。
获取方法
11)测试Get方法REST服务URL:"http://localhost:8080/JAXRSJSONCRUDEXAMPLE/REST/C国家"。
我们将获取以下输出:
发布方法
12)POST方法用于创建新资源。
其中我们正在将新的国家英格兰添加到国家列表,因此我们可以看到我们在邮政机构中使用了新的国家json。
URL:"http://localhost:8080/JAXRSJSONCRUDEXAMPLE/REST /国家"。
使用get方法检查上述国家是否已添加到国家/地区列表。
施列方法
13)PUT方法用于更新资源。
这里将使用PUT方法更新尼泊尔群体。
我们将在请求主体中更新国家json。
URL:"http://localhost:8080/JAXRSJSONCRUDEXAMPLE/REST /国家"
使用GET方法检查尼泊尔人口。
删除方法
14)删除方法用于删除资源。
我们将传递需要删除为pathparam的国家/地区。
我们要删除ID:4。
URL:"http://localhost:8080/JAXRSJSONCRUDEXAMPLE/REST/COUNDY/4"

