码迷,mamicode.com
首页 > 编程语言 > 详细

springMVC+json构建restful风格的服务

时间:2017-07-30 13:44:34      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:override   encoding   slist   lis   port   last   UI   配置   reserve   

首先。要知道什么是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风格的服务

标签:override   encoding   slist   lis   port   last   UI   配置   reserve   

原文地址:http://www.cnblogs.com/mthoutai/p/7258843.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!