Spring MVC RESTFul Web Service CRUD 例子

本文主要翻译自:http://memorynotfound.com/spring-mvc-restful-web-service-crud-example/

本文主要讲解如何使用Spring MVC4搭建RestFul Web service。我们新建一个进行CRUD操作的controller,使用http方法的POST、GET、PUT、DELETE来区分新建、查询、修改、删除。这个rest service使用json进行数据传输。我们使用CrossOrigin来解决跨域问题。

Rest Controller

使用spring MVC4实现 一个REST Web Service 有很多种方式,我们选取下面这种最简单的。使用ResponseEntity直接控制response的响应头和http状态码。

  • http GET方法 /users 请求全部用户数据
  • http GET方法 /users/1 请求id为1的用户
  • http POST方法 /users 使用json格式新建一个用户
  • http PUT方法 /users/1 修改id为1的用户
  • http DELETE方法 /users/1 删除id为1的用户
package com.memorynotfound.controller;

import com.memorynotfound.model.User;
import com.memorynotfound.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;
import java.util.List; @RestController
@RequestMapping("/users")
public class UserController { private final Logger LOG = LoggerFactory.getLogger(UserController.class); @Autowired
private UserService userService; // =========================================== Get All Users ========================================== @RequestMapping(method = RequestMethod.GET)
public ResponseEntity<List<User>> getAll() {
LOG.info("getting all users");
List<User> users = userService.getAll(); if (users == null || users.isEmpty()){
LOG.info("no users found");
return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);
} return new ResponseEntity<List<User>>(users, HttpStatus.OK);
} // =========================================== Get User By ID ========================================= @RequestMapping(value = "{id}", method = RequestMethod.GET)
public ResponseEntity<User> get(@PathVariable("id") int id){
LOG.info("getting user with id: {}", id);
User user = userService.findById(id); if (user == null){
LOG.info("user with id {} not found", id);
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
} return new ResponseEntity<User>(user, HttpStatus.OK);
} // =========================================== Create New User ======================================== @RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Void> create(@RequestBody User user, UriComponentsBuilder ucBuilder){
LOG.info("creating new user: {}", user); if (userService.exists(user)){
LOG.info("a user with name " + user.getUsername() + " already exists");
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
} userService.create(user); HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
} // =========================================== Update Existing User =================================== @RequestMapping(value = "{id}", method = RequestMethod.PUT)
public ResponseEntity<User> update(@PathVariable int id, @RequestBody User user){
LOG.info("updating user: {}", user);
User currentUser = userService.findById(id); if (currentUser == null){
LOG.info("User with id {} not found", id);
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
} currentUser.setId(user.getId());
currentUser.setUsername(user.getUsername()); userService.update(user);
return new ResponseEntity<User>(currentUser, HttpStatus.OK);
} // =========================================== Delete User ============================================ @RequestMapping(value = "{id}", method = RequestMethod.DELETE)
public ResponseEntity<Void> delete(@PathVariable("id") int id){
LOG.info("deleting user with id: {}", id);
User user = userService.findById(id); if (user == null){
LOG.info("Unable to delete. User with id {} not found", id);
return new ResponseEntity<Void>(HttpStatus.NOT_FOUND);
} userService.delete(id);
return new ResponseEntity<Void>(HttpStatus.OK);
}
}
  • @RestController 只是@Controller 和@ResponseBody的简化使用。就是使用了@RequestController后不再需要在每个方法上设置@ResponseBody。
  • @RequestMapping 是个老朋友了,就是url到控制器的映射关系定义,这边主要是使用url+http方法进行定义。一般在类上定义根url,如/users,然后在每个方法上在此基础上定义。
  • @PathVariable 方法参数从uri中提取。Spring MVC需要从URI模板中通过name查找参数值,然后注入到方法中。
  • @RequestBody 暗示方法参数绑定到请求体中的数据。一个HttpMessageConverter会负责将请求体中的json数据转化并装配到参数中。
  • @ResponseBody 暗示返回的数据直接写入到Response body中。就像上面说的,使用了@RestController后不再需要设置。
  • ResponseEntity 作为HttpEntity的子类,可以设置HttpStatus 状态码。ResponseEntity代码整个HTTP响应,可以添加响应头,状态码,并设置Response body。
  • HttpHeaders 表示 HTTP 的 请求头和响应头。这个类可以方便地设置Content-Type和Access-Content-Allow-Headers等。

CorsFilter

跨域问题直接使用Spring MVC提供的CorsFilter可以简单解决或者在xml中设置mvc:cors

<filter>
<filter-name>cors</filter-name>
<filter-class>org.springframework.web.filter.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

具体可以查看: spring MVC cors跨域实现源码解析

maven依赖


<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>
<groupId>com.memorynotfound.spring.mvc.rest</groupId>
<artifactId>crud</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>SPRING-MVC - ${project.artifactId}</name>
<url>http://memorynotfound.com</url>
<packaging>war</packaging> <properties>
<spring.version>4.2.6.RELEASE</spring.version>
<jackson.version>2.7.4</jackson.version>
<logback.version>1.1.7</logback.version>
</properties> <dependencies>
<!-- spring libraries -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency> <!-- Needed for JSON View -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency> <!-- logging -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency> <!-- servlet api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build> </project>

[翻译]Spring MVC RESTFul Web Service CRUD 例子的更多相关文章

  1. 构建一个基于 Spring 的 RESTful Web Service

    本文详细介绍了基于Spring创建一个“hello world” RESTful web service工程的步骤. 目标 构建一个service,接收如下HTTP GET请求: http://loc ...

  2. 【转】Building a RESTful Web Service

    目标 构建一个service,接收如下HTTP GET请求: [plain] view plain copy   http://localhost:8080/greeting 并返回如下JSON格式的 ...

  3. 【转】基于CXF Java 搭建Web Service (Restful Web Service与基于SOAP的Web Service混合方案)

    转载:http://www.cnblogs.com/windwithlife/archive/2013/03/03/2942157.html 一,选择一个合适的,Web开发环境: 我选择的是Eclip ...

  4. 用Spring Tools Suite(STS)开始一个RESTful Web Service

    spring.io官方提供的例子Building a RESTful Web Service提供了用Maven.Gradle.STS构建一个RESTFul Web Service,实际上采用STS构建 ...

  5. Building a RESTful Web Service Using Spring Boot In Eclipse

    一.构建restful web service 创建Maven的java web工程,maven的pom文件加入依赖包 创建包hello Greeting.java package hello; pu ...

  6. Apache CXF实现Web Service(4)——Tomcat容器和Spring实现JAX-RS(RESTful) web service

    准备 我们仍然使用 Apache CXF实现Web Service(2)——不借助重量级Web容器和Spring实现一个纯的JAX-RS(RESTful) web service 中的代码作为基础,并 ...

  7. Apache CXF实现Web Service(3)——Tomcat容器和不借助Spring的普通Servlet实现JAX-RS(RESTful) web service

    起步 参照这一系列的另外一篇文章: Apache CXF实现Web Service(2)——不借助重量级Web容器和Spring实现一个纯的JAX-RS(RESTful) web service 首先 ...

  8. 【转】Spring 4.x实现Restful web service

    http://my.oschina.net/yuyidi/blog/352909 首先我们还是跟之前一样,创建一个maven项目,不过因为Spring Restful web service是基于Sp ...

  9. 在GlassFish应用服务器上创建并运行你的第一个Restful Web Service【翻译】

    前言 本人一直开发Android应用,目前Android就业形势恶劣,甚至会一路下滑,因此决定学习服务器开发.采用的语言是java,IDE是Intellij,在下载Intellij的同时看到官网很多优 ...

随机推荐

  1. java 观察者模式 与spring配置

    一.Observer模式的意图: 在对象的内部状态发生变化时,自动通知外部对象进行响应. 二.Observer模式的构成: ·被观察者:内部状态有可能被改变,而且又需要通知外部的对象 ·观察者:需要对 ...

  2. mongodb基础学习1-基本说明及安装

    以前看过一些mongodb的视频,但只看到一半没有看完,也没有同步安装软件动手操作,正好最近没事,打算花点时间从头学习一遍,边学习边动手操作,学习的过程在此进行记录. 好了,下面说一下今天的学习内容. ...

  3. 数据恢复软件extundelete介绍

    linux下文件系统一般由文件名.Inode.Block三部分组成.当一个用户在Linux系统中试图访问一个文件时,系统会先根据文件名去查找它的inode,看该用户是否具有访问这个文件的权限.如果有, ...

  4. Kotlin语言学习笔记(5)

    委托模式(Delegation) 类的委托 interface Base { fun print() } class BaseImpl(val x: Int) : Base { override fu ...

  5. 如何将Wav文件做到EXE文件里

    1)编写.RC文件 ..RC文件是资源的源文件,编译器也就编译这个文件,生成.RES的资源文件 首先在我们的项目子目录中建立一个纯文本文件,起名叫Sound.rc,文件中 有一行,内容为: SOUND ...

  6. tomcat 管理端 安全措施

    由于公司的项目并未启用nginx负载均衡,所以自然也没用到tomcat与web应用一对一的安全操作,经常会遇到 重启单个应用又不想重启tomcat的情况.同时,又出于安全考虑,将tomcat的默认管理 ...

  7. jQuery源码解读二(apply和call)

    一.apply方法和call方法的用法: apply方法: 语法:apply(thisObj,[,argArray]) 定义:应用某一对象的一个方法,用另一个对象替换当前对象. 说明:如果argArr ...

  8. Dom对象总结介绍&事件介绍&增删查找标签

    1.dom有5个属性,属性内容如下 下面开始介绍Dom属性,一共有5个属性 1.document object:文档对象 2.element object:标签对象 3.test object:文本对 ...

  9. collections之deque【双向队列】与Queue【单向队列】

    今天来向大家介绍两个队列,一个是deque,双向队列,另外一个是Queue,单向队列,队列和堆栈不同,队列为先进先出,大家还需要注意一下,双向队列为collections模块中的类,而Queue为qu ...

  10. [leetcode]174. Dungeon Game地牢游戏

    The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. ...