首先。要知道什么是rest服务,什么是rest服务呢?

REST(英文:Representational State Transfer,简称REST)描写叙述了一个架构样式的网络系统。比方 web 应用程序。

它首次出如今 2000 年 Roy Fielding 的博士论文中,他是 HTTP 规范的主要编写者之中的一个。

在眼下主流的三种Web服务交互方案中。REST相比于SOAP(Simple Object Access protocol,简单对象訪问协议)以及XML-RPC更加简单明了,不管是对URL的处理还是对Payload的编码,REST都倾向于用更加简单轻量的方法设计和实现。值得注意的是REST并没有一个明白的标准,而更像是一种设计的风格。

rest是以资源为中心。将一个一个请求作出的响应以资源的形式返回,可能你请求的是一个xml,一个html。rest都把它归类为资源。也就是说全部的响应都是基于资源的。

而REST的web service 设计原则是基于CRUD,其支持的四种操作分别为:

GET – 获取信息/请求信息内容。绝大多数浏览器获取信息时使用该方式。

POST – 添加信息内容。显示曾经的信息内容,能够看作是insert操作

PUT – 更新信息内容。相当与update

DELETE – 删除信息内容能够看作是delete

我们平时一般仅仅用上面的get和post方法,而非常少使用其它方法。事实上http还有put、delete、head方法。

而且REST 的请求和响应也是使用http的request和response俩实现的。

在这里我将使用springMVC+json的形式构建一个restful风格的demo。

首先springMVC环境搭建:

相关jar包:

spring配置文件applicationContext.xml:

<?

xml version="1.0" encoding="UTF-8"?

>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <!-- 载入外部的properties配置文件 -->
<context:property-placeholder location="classpath:/config/jdbc.properties" />
<context:component-scan base-package="com.gisquest"/>
<!-- 配置数据库连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<!-- 连接数据库驱动 -->
<property name="driverClass" value="${driverClass}"></property>
<!-- 数据库url -->
<property name="jdbcUrl" value="${jdbcUrl}"></property>
<!-- 数据库用户名 -->
<property name="user" value="${user}"></property>
<!-- 数据库密码-->
<property name="password" value="${password}"></property> <!-- 其它配置--> <!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。 Default: 3 -->
<property name="initialPoolSize" value="3"></property>
<!--连接池中保留的最小连接数。 Default: 3 -->
<property name="minPoolSize" value="3"></property>
<!--连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize" value="5"></property>
<!--当连接池中的连接耗尽的时候c3p0一次同一时候获取的连接数。Default: 3 -->
<property name="acquireIncrement" value="3"></property>
<!-- 控制数据源内载入的PreparedStatements数量。假设maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0 -->
<property name="maxStatements" value="8"></property>
<!-- maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0 -->
<property name="maxStatementsPerConnection" value="5"></property>
<!--最大空暇时间,1800秒内未使用则连接被丢弃。 若为0则永不丢弃。 Default: 0 -->
<property name="maxIdleTime" value="1800"></property>
</bean>
<!-- 配置SqlsessionFactory-->
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:/config/mapper/*Mapper.xml"/>
<property name="typeAliasesPackage" value="com.gisquest.bean"></property>
</bean> <!-- mapper扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描包路径。假设须要扫描多个包,中间使用半角逗号隔开 -->
<property name="basePackage" value="com.gisquest.dao"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

springMVC配置文件:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <!-- 注解驱动 -->
<mvc:annotation-driven />
<!-- 激活spring注解方式:自己主动扫描,并注入bean
-->
<context:component-scan base-package="com.gisquest"/> <bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置jsp路径的前缀 -->
<property name="prefix" value="/WEB-INF/pages/"/>
<!-- 配置jsp路径的后缀 -->
<property name="suffix" value=".jsp"/>
</bean> <bean id="stringConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean> <!-- 输出对象转JSON支持 -->
<bean id="jsonConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="stringConverter"/>
<ref bean="jsonConverter" />
</list>
</property>
</bean> <!-- 文件上传 -->
</beans>

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" id="WebApp_ID" version="3.0">
<welcome-file-list>
<welcome-file>WEB-INF/pages/index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- springmvc配置 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<description>spring mvc 配置文件</description>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<description>字符集过滤器</description>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<description>字符集编码</description>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- 解决HTTP PUT请求Spring无法获取请求參数的问题 -->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<servlet-name>springMVC3</servlet-name>
</filter-mapping>
</web-app>

该demo使用了mybatis来操作持久层,以下是mapper文件,userMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?

>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- namespace命名空间。作用就是对sql进行分类化管理。理解sql隔离
注意:使用mapper代理方法开发,namespace有特殊关键的数据。namespace等于mapper接口地址
-->
<mapper namespace="com.gisquest.dao.UserMapper"> <!-- sql片段 -->
<sql id="sql_where_dymatic">
<if test="username!=null">
AND username=#{username}
</if>
<if test="address!=null">
AND address=#{address}
</if>
</sql> <resultMap type="User" id="aliasResultMap">
<id column="id_" property="id"/>
<result column="name_" property="username"/>
<result column="address_" property="address"/>
</resultMap>
<!-- sql综合查询 -->
<select id="findDynamic" resultType="User" parameterType="map">
SELECT * FROM user
<where>
<include refid="sql_where_dymatic"></include>
</where>
</select>
<!-- 通过id查找 -->
<select id="findByUserId" resultType="User" parameterType="Long">
SELECT * FROM user WHERE id=#{id}
</select> <!-- 通过id查找,可是查找的列名是别名 -->
<select id="findByAlias" resultType="String" parameterType="Long">
SELECT username name FROM user u WHERE u.id=#{id}
</select>
<!-- 通过resultMap输出 -->
<select id="findByMap" resultMap="aliasResultMap" parameterType="Long">
SELECT id id_ ,username name_ ,address address_ FROM user u WHERE u.id=#{id}
</select>
<!-- 插入数据 -->
<insert id="insertUser" parameterType="User">
<!-- 本来主键是自增的,在插入数据时还没有插入主键,所以将插入的主键返回到user对象中 -->
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO user(username,sex,birthday,address) VALUE(#{username},#{sex},#{birthday},#{address})
</insert>
<!-- 更新数据 -->
<update id="updateUser" parameterType="User">
UPDATE user SET username=#{username},sex=#{sex},birthday=#{birthday},address=#{address} WHERE id=#{id}
</update> <delete id="deleteUserById" parameterType="Long">
DELETE FROM user WHERE id=#{id}
</delete>
<resultMap type="User" id="UserOderResultMap">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="sex" property="sex"/>
<result column="birthday" property="birthday"/>
<result column="address" property="address"/>
<collection property="ordersList" ofType="Orders">
<id column="userId" property="userId"/>
<result column="createtime" property="createtime"/>
<result column="number" property="number"/>
<result column="createtime" property="userId"/>
<result column="note" property="note"/>
</collection>
</resultMap>
<select id="findUserOrderMap" resultMap="UserOderResultMap">
select user.*,orders.number,orders.note,orders.createtime from orders, user where orders.userId=user.id
</select> </mapper>

javabean:

package com.gisquest.bean;

import java.util.List;

public class User {

    private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
private String username;
private int sex;
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
} public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
} public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
private String birthday;
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
private String address;
private List<Orders> ordersList;
public List<Orders> getOrdersList() {
return ordersList;
}
public void setOrdersList(List<Orders> ordersList) {
this.ordersList = ordersList;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", sex=" + sex
+ ", birthday=" + birthday + ", address=" + address + "]";
} }

dao层:

package com.gisquest.dao;

import java.util.List;
import java.util.Map; import org.springframework.stereotype.Repository; import com.gisquest.bean.User;
@Repository
public interface UserMapper { public User findByUserId(Long id); public void insertUser(User user);
//更新user
public void updateUser(User user);
//删除特定user
public void deleteUserById(Long id);
//使用sql片段动态查询
public List<User> findDynamic(Map paramMap);
//使用别名查
public String findByAlias(Long id);
public User findByMap(Long id);
//userorders关联查询
public List<User> findUserOrderMap();
}

service层:

/**
* @Project : test Maven Webapp
* @Title : UserService.java
* @Package com.gisquest.service
* @Description :
* @author laiyao
* @Copyright : 2015 zhejiang shine Technology Co. Ltd All right reserved.
* @date 2015年6月26日 下午12:40:45
* @version V1.0
*/
package com.gisquest.service; import com.gisquest.bean.User; /**
* @ClassName: UserService
* @Description:
* @author: laiyao
* @date: 2015年6月26日下午12:40:45
*/
public interface UserService { public User findByUserId(Long id); public void insert(User user); public void update(User user); public void delete(Long id); }

service实现类:

/**
* @Package com.gisquest.service.Impl
* @Description :
* @author laiyao
* @Copyright : 2015 zhejiang shine Technology Co. Ltd All right reserved.
* @date 2015年6月26日 下午12:42:04
* @version V1.0
*/
package com.gisquest.serviceImpl; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import com.gisquest.bean.User;
import com.gisquest.dao.UserMapper;
import com.gisquest.service.UserService; /**
* @ClassName: UserServiceImpl
* @Description:
* @author: laiyao
* @date: 2015年6月26日下午12:42:04
*/
@Service
@Transactional
public class UserServiceImpl implements UserService{
@Autowired
private UserMapper userMapper; public void findByUserId1() {
// TODO Auto-generated method stub
User user=userMapper.findByUserId(1L);
System.out.println(user);
} public User findByUserId(Long id) {
// TODO Auto-generated method stub
return userMapper.findByUserId(id);
}
@Override
public void insert(User user) {
// TODO Auto-generated method stub
userMapper.insertUser(user);
}
@Override
public void update(User user) {
// TODO Auto-generated method stub
userMapper.updateUser(user);
}
@Override
public void delete(Long id) {
userMapper.deleteUserById(id);
} }

controller层:

package com.gisquest.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

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.ResponseBody;

import com.gisquest.bean.User;

import com.gisquest.service.UserService;

@Controller

@RequestMapping(“/”)

public class UserController {

@Autowired
private UserService userService; @RequestMapping(value="/show",method=RequestMethod.POST)
public String show(Model model){
User user=userService.findByUserId(1L);
model.addAttribute("user", user);
return "index";
}
/**
*
* @description : 查询
* @author :laiyao
* @date :2015年8月17日
*/
@RequestMapping(value="/show2",method=RequestMethod.GET)
public @ResponseBody User show2(Model model,HttpServletRequest request){
User user=userService.findByUserId(1L);
model.addAttribute("user", user);
return user;
}
/**
*
* @description : 插入一条数据
* @author :laiyao
* @date :2015年8月17日
*/
@RequestMapping(value="/insert",method=RequestMethod.POST,produces = "application/json")
public @ResponseBody String insert(@RequestBody User user,HttpServletRequest request){
userService.insert(user);
return "保存user成功";
}
/**
*
* @description : 更新user
* @author :laiyao
* @date :2015年8月17日
*/
@RequestMapping(value="/update/{id}",method=RequestMethod.PUT,produces = "application/json")
public @ResponseBody User update(@PathVariable Long id,@RequestBody User user,HttpServletRequest request){
User users=userService.findByUserId(id);
users.setAddress(user.getAddress());
users.setBirthday(user.getBirthday());
users.setSex(user.getSex());
users.setUsername(user.getUsername());
userService.update(users);
return users;
} /**
*
* @description : 删除user
* @author :laiyao
* @date :2015年8月17日
*/
@RequestMapping(value="/delete/{id}",method=RequestMethod.DELETE,produces="application/json")
public @ResponseBody String delete(@PathVariable Long id,HttpServletRequest request){
userService.delete(id);
return "delete user has finished";
}

}

在这里面最重要的是@ResponseBody和@RequestBody这两个注解,这两个注解就是来获取请求參数和返回资源用的。

接着再測试一下:

删除:



新增:



更新:

springMVC+json构建restful风格的服务的更多相关文章

  1. springmvc+swagger构建Restful风格文档

    本次和大家分享的是java方面的springmvc来构建的webapi接口+swagger文档:上篇文章分享.net的webapi用swagger来构建文档,因为有朋友问了为啥.net有docpage ...

  2. lucene构建restful风格的简单搜索引擎服务

    来自于本人博客: lucene构建restful风格的简单搜索引擎服务 本人的博客如今也要改成使用lucene进行全文检索的功能,因此在这里把代码贴出来与大家分享 一,文件夹结构: 二,配置文件: 总 ...

  3. 构建RESTful风格的WCF服务

    构建RESTful风格的WCF服务 RESTful Wcf是一种基于Http协议的服务架构风格. 相较 WCF.WebService 使用 SOAP.WSDL.WS-* 而言,几乎所有的语言和网络平台 ...

  4. SpringMVC 构建Restful风格 及问题处理

    基本的请求URL: /person/{id}  GET  得到id的person /person POST      新增person /person/{id}  PUT  更新id的person / ...

  5. Spring Boot构建 RESTful 风格应用

    Spring Boot构建 RESTful 风格应用 1.Spring Boot构建 RESTful 风格应用 1.1 实战 1.1.1 创建工程 1.1.2 构建实体类 1.1.4 查询定制 1.1 ...

  6. SpringMVC+Json构建基于Restful风格的应用(转)

    一.spring 版本:spring-framework-3.2.7.RELEASE 二.所需其它Jar包: 三.主要代码: web.xml <?xml version="1.0&qu ...

  7. SpringBoot实战(一)之构建RestFul风格

    RestFul风格是一种非常流行的架构风格,相关实战可以参考我的这篇博客:SSM框架之RestFul示例 论文可参考:https://www.ics.uci.edu/~fielding/pubs/di ...

  8. Spring Boot 中 10 行代码构建 RESTful 风格应用

    RESTful ,到现在相信已经没人不知道这个东西了吧!关于 RESTful 的概念,我这里就不做过多介绍了,传统的 Struts 对 RESTful 支持不够友好 ,但是 SpringMVC 对于 ...

  9. Spring Boot2 系列教程(三十一)Spring Boot 构建 RESTful 风格应用

    RESTful ,到现在相信已经没人不知道这个东西了吧!关于 RESTful 的概念,我这里就不做过多介绍了,传统的 Struts 对 RESTful 支持不够友好 ,但是 SpringMVC 对于 ...

随机推荐

  1. Avoiding memory leaks in POSIX thread programming, 多线程避免内存泄漏

    默认创建的线程为joinable的,必须调用pthread_join()才可以释放所占的内存 创建分离线程detach, attr 线程函数运行结束,调用pthread_exit 其它线程调用pthr ...

  2. 玩具谜题(NOIP2016)(纯模拟)

    原题传送门 神奇的题目.. 朝左朝右异或一下就好了 细节处理一下,输出now的字符串 下面贴代码 #include<iostream> #include<cstdio> #in ...

  3. 动态加载.so文件并执行类函数

    背景:不同产品组将其功能编译为.so,这些.so 可以加载到统一的基础平台上运行,如果产品组代码有改动,只需要更新对应的.so 问题:如何动态加载.so文件,并使用里边的函数/类 ? 解决方法1: 使 ...

  4. 解决:java.lang.ArrayIndexOutOfBoundsException: 160 at com.alibaba.fastjson.serializer.SerializeWriter.writeStringWithDoubleQuote(SerializeWriter.java:868)

    今天线上遇到一个问题,从hbase里读取出来的数据在转换json后输出时出现异常: java.lang.ArrayIndexOutOfBoundsException: 160 at com.aliba ...

  5. centos7使用tomcat部署javaweb项目

    1.下载二进制安装包 tomcat下载地址 2.下载jdk和配置环境变量 这里就不再多描述不清楚,可以       参考 我的yum安装的jdk 3.在centos7下安装 tomcat #切换到/u ...

  6. Sublime Text 3 使用技巧,插件

    一.安装 官网下载最新版安装包,地址自行百度,或者我的网盘 不要安装某些网站提供的安装包*3,原因如下: 1,安装过程捆绑一些不必要的软件 2,测试过程中,某些功能受到限制 快捷键大全 3,一些设置, ...

  7. js中立即执行函数写法理解

    在理解了一些函数基本概念后,回头看看( function(){…} )()和( function (){…} () )这两种立即执行函数的写法,最初我以为是一个括号包裹匿名函数, 并后面加个括号立即调 ...

  8. 系统封装的dispatch系列代码块引起的循环引用

    整整一天的时间都在找内存泄漏,唯独遗漏了这个代码块,结果就是它,希望大家以后注意. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)( ...

  9. (11)C#值类型和引用类型,堆和栈,ref和out,装箱和拆箱

    一.值类型和引用类型定义 以内存中的存在方式可以把变量分成两大类型,值类型和引用类型. 值类型:系统只占用一块内存,数据直接存储在内存里. 引用类型:系统占用两块内存,一块存放地址,另一块存放实际数据 ...

  10. Python的支持工具[1] -> 可执行文件生成工具[1] -> cx_freeze

    cx_freeze cx_Freeze 是一个第三方库,可以用于将 Python 的代码打包成可执行文件,下面介绍如何利用一个脚本文件将 Python 代码变为 exe 可执行文件. 首先,需要安装 ...