Spring Restful Web服务Crud示例
在本教程中,我们将看到Spring Restful Web Services Crud示例。
在本教程中,我们将扩展相同的示例并创建RESTful Web服务,它将提供CRUD(创建,读取,更新和删除)操作示例。
如果我们希望与Hibernate和MySQL完整集成,我们可以通过Spring Restful Hibernate MySQL示例。
我们将使用以下注释进行Crud操作。
| 方法 | 描述 |
|---|---|
| Get | 它用于读取资源 |
| Post | 它用于创建新资源。不是Idempotent方法 |
| Put | 它通常用于更新资源。它是idempotent方法 |
| Delete | 它用于删除资源 |
idempotent意味着多个成功请求的结果不会在初始应用程序之后更改资源状态:删除是幂等的方法,因为当第一次使用删除时,它将删除资源(初始应用程序),但之后,所有其他请求都没有结果,因为资源已被删除。
POST不是IDEMPOTENT方法,因为当我们使用POST创建资源时,它将继续为每个新请求创建资源,因此多个成功请求的结果将不相同。
以下是创建Spring休眠Web服务的步骤
1)使用名为"springrestfulwebservicescrudexample"的Eclipse中使用Maven创建动态Web项目
Maven依赖项
2)我们需要在类路径中添加Hymanson Json实用程序。
<dependency>
<groupId>com.fasterxml.Hymanson.core</groupId>
<artifactId>Hymanson-databind</artifactId>
<version>2.4.1</version>
</dependency>
Spring将Hymanson2jsonmessageConverter自动加载到其应用程序上下文中。
每当我们使用Accep Headers ="Accept = Application/JSON"时请求资源作为JSON,那么Hymanson2jsonMessageConverter就会进入图片并将资源转换为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>SpringRestfulWebServicesWithJSONExample</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringRestfulWebServicesWithJSONExample Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.Hymanson.core</groupId>
<artifactId>Hymanson-databind</artifactId>
<version>2.4.1</version>
</dependency>
</dependencies>
<build>
<finalName>SpringRestfulWebServicesWithJSONExample</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<spring.version>4.2.1.RELEASE</spring.version>
<jdk.version>1.7</jdk.version>
</properties>
</project>
Spring应用程序配置:
3)更改Web.xml如下:
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <servlet> <servlet-name>springrest</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springrest</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
4)在/Web-Inf /文件夹中创建名为springrest-servlet.xml的XML文件。
请更改上下文:组件扫描如果要使用不同的套装来搜索控制器。
请参阅Spring MVC Hello World示例以获取更多的理解。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven
<context:component-scan base-package="org.igi.theitroad.controller"
</beans>
创建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 org.igi.theitroad.bean.Country;
import org.igi.theitroad.service.CountryService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CountryController {
CountryService countryService = new CountryService();
@RequestMapping(value = "/countries", method = RequestMethod.GET, headers = "Accept=application/json")
public List getCountries() {
List listOfCountries = countryService.getAllCountries();
return listOfCountries;
}
@RequestMapping(value = "/country/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
public Country getCountryById(@PathVariable int id) {
return countryService.getCountry(id);
}
@RequestMapping(value = "/countries", method = RequestMethod.POST, headers = "Accept=application/json")
public Country addCountry(@RequestBody Country country) {
return countryService.addCountry(country);
}
@RequestMapping(value = "/countries", method = RequestMethod.PUT, headers = "Accept=application/json")
public Country updateCountry(@RequestBody Country country) {
return countryService.updateCountry(country);
}
@RequestMapping(value = "/country/{id}", method = RequestMethod.DELETE, headers = "Accept=application/json")
public void deleteCountry(@PathVariable("id") int id) {
countryService.deleteCountry(id);
}
}
创建服务类
6)在package org.igi.theitroad.onitoad.service中创建一个countryservice.java .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(getMaxId()+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;
}
//Utility method to get max id
public static int getMaxId()
{ int max=0;
for (int id:countryIdMap.keySet()) {
if(max<=id)
max=id;
}
return max;
}
}
7)这是时候做Maven建造了。
右键单击项目 - >运行AS - > Maven Build
8)将目标作为清洁安装(下面给出),然后单击运行
运行应用程序
9)右键单击项目 - >在服务器上运行AS - >运行
选择Apache Tomcat,然后单击"完成"
10)我们将在邮递员,基于UI的客户端测试此应用程序,用于测试RESTful Web应用程序。
它是Chrome插件。
启动Postman.如果我们希望基于Java的客户端,那么我们还可以使用如何在Java中发送Get或者Post请求。
get方法
11)测试Get方法Spring Rest Service URL:"http://localhost:8080/springrestfulwebservicescrudescrexample/countries"。
post方法
12)POST方法用于创建新资源。
其中我们正在将新的国家英格兰添加到国家列表,因此我们可以看到我们在邮政机构中使用了新的国家json。
URL:"http://localhost:8080/springrestfulwebservicescrudescrudexample/countries"。
put方法
13)PUT方法用于更新资源。
这里将使用PUT方法更新尼泊尔群体。
我们将在请求主体中更新国家json。
URL:"http://localhost:8080/springrestfulwebservicescrudescrexample/countries"
delete方法
14)删除方法用于删除资源。
我们要删除ID4。
URL:"http://localhost:8080/springrestfulwebservicescrudescrudexample/country/4"

