1. 程式人生 > >springMVC+json構建restful風格的服務

springMVC+json構建restful風格的服務

響應 driver 服務 dispatch project ado test idle ransac

首先。要知道什麽是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";
}

}
[email protected]@RequestBody這兩個註解,這兩個註解就是來獲取請求參數和返回資源用的。
接著再測試一下:
刪除:
技術分享
新增:
技術分享
更新:
技術分享

springMVC+json構建restful風格的服務