spring mvc restful + json 测试代码(二)

本文介绍了一个基于RESTful架构的Spring MVC JSON测试案例,包括人员信息的增删改查操作。

4. Person.java

package com.kakaka.restful.domain;

public class Person {

	private int id;
	private String name;
	private String sex;
	private int age;
	
	....省略setter、getter方法
}

5. PersonController.java

    注意:

package com.kakaka.restful.web.controller;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gzdfbz.restful.domain.Person;

/**
 * 基于Restful风格架构测试
 * 根据请求方式不同,可做如下约定:
 * /person/{id} HTTP GET    => get()
 * /person/{id} HTTP DELETE => delete()
 * /person       HTTP POST   => add()
  * /person       HTTP PUT   => addOrUpdate() 新增或完整更新(不太好用),就是所有属性不管更新还是不更新,都要列出来。
 * /person      HTTP PATCH  => update() 部分更新 
 *
@Controller
public class PersonController {

	/** logback 日志实例 */
	private final static Logger logger = LoggerFactory
			.getLogger("PersonController.class");

	/**
	 * 获取人员信息
	 * /person/{id} HTTP GET => get()
	 * @return
	 */
	@RequestMapping(value = "/person/{id:\\d+}", method = RequestMethod.GET)
	public @ResponseBody 
	Person getPerson(@PathVariable("id") int id) {
		logger.info("获取人员信息id=" + id);
		Person person = new Person();
		person.setName("张三");
		person.setSex("男");
		person.setAge(30);
		person.setId(id);
		return person;
	}

	/**
	 * 删除人员信息
	 * /person/{id} HTTP DELETE => delete()
	 * @return
	 */
	@RequestMapping(value = "/person/{id:\\d+}", method = RequestMethod.DELETE)
	public @ResponseBody 
	Object delete(@PathVariable("id") int id) {
		logger.info("删除人员信息id=" + id);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("msg", "删除人员信息成功");
		return jsonObject;
	}

	/**
	 * 添加人员信息
	 * /person HTTP POST =>  add()
	 * @return
	 */
	@RequestMapping(value = "/person", method = RequestMethod.POST)
	public @ResponseBody 
	Object add(Person person) {
		logger.info("添加人员信息成功id=" + person.getId());
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("msg", "添加人员信息成功");
		return jsonObject;
	}

	/**
	 * 更新人员信息
	 * /person/{id} PUT => update()
	 * @return
	 */
	@RequestMapping(value = "/person", method = RequestMethod.PUT)
	public @ResponseBody Object update(Person person) {
		logger.info("更新人员信息id=" + person.getId());
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("msg", "更新人员信息成功");
		return jsonObject;
	}

	/**
	 * 获取人员信息列表
	 * /person HTTP PATCH=>  update()
	 * @return
	 */
	@RequestMapping(value = "/person", method = RequestMethod.PATCH)
	public @ResponseBody List<Person> update(
			@RequestParam(value = "name", required = false, defaultValue = "") String name){

		logger.info("name like " + name);
		List<Person> lstPersons = new ArrayList<Person>();

		Person person = new Person();
		person.setName("张三");
		person.setSex("男");
		person.setAge(25);
		person.setId(101);
		lstPersons.add(person);

		Person person2 = new Person();
		person2.setName("李四");
		person2.setSex("女");
		person2.setAge(23);
		person2.setId(102);
		lstPersons.add(person2);

		Person person3 = new Person();
		person3.setName("王五");
		person3.setSex("男");
		person3.setAge(27);
		person3.setId(103);
		lstPersons.add(person3);

		return lstPersons;
	}

}

6. 页面 rest.jsp

   注意:在http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html 中同时指明:

contentType: "application/x-www-form-urlencoded"

   rest.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page contentType="text/html;charset=UTF-8"%>
<c:set var="ctx" value="${pageContext.request.contextPath}" />

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>spring mvc restful json test</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">
	<meta http-equiv="keywords" content="spring,webmvc,restful,json,ajax">
	<meta http-equiv="description" content="spring mvc restful json test">
	<link rel="stylesheet" type="text/css"	href="uikit-2.8.0/css/uikit.gradient.min.css">
	<link rel="stylesheet" type="text/css" href="uikit-2.8.0/css/addons/uikit.gradient.addons.min.css">
</head>
<body>
<div
	style="width:800px;margin-top:10px;margin-left: auto;margin-right: auto;text-align: center;">
	<h2>spring mvc restful json test</h2>
</div>
<div style="width:800px;margin-left: auto;margin-right: auto;">
	<fieldset class="uk-form">
		<legend>表单测试</legend>
		<div class="uk-form-row">
			<input type="text" class="uk-width-1-1">
		</div>
		<div class="uk-form-row">
			<input type="text" class="uk-width-1-1 uk-form-success">
		</div>
		<div class="uk-form-row">
			<input type="text" class="uk-width-1-1 uk-form-danger">
		</div>
		<div class="uk-form-row">
			<input type="text" class="uk-width-1-1">
		</div>
		<div class="uk-form-row">
			<select id="form-s-s">
				<option>---请选择---</option>
				<option>是</option>
				<option>否</option>
			</select>
		</div>
		<div class="uk-form-row">
			<input type="date" id="form-h-id" />
		</div>
	</fieldset>
	<fieldset class="uk-form">
		<legend>基于Restful架构风格的资源请求测试</legend>
		<button class="uk-button uk-button-primary uk-button-large" id="btnGet">获取人员GET</button>
		<button class="uk-button uk-button-primary uk-button-large" id="btnAdd">添加人员POST</button>
		<button class="uk-button uk-button-primary uk-button-large" id="btnUpdate">更新人员PUT</button>
		<button class="uk-button uk-button-danger uk-button-large" id="btnDel">删除人员DELETE</button>
		<button class="uk-button uk-button-primary uk-button-large" id="btnList">查询列表PATCH</button>
	</fieldset>
</div>
 <div align="center">
        <br> <br>=========测试测试测试=======<br> <br>
        <div id="result"></div>
        <br>
        <p>
            by <a href="http://gzdfbz.com">gzdfbz.com</a>
        </p>
    </div>

<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="uikit-2.8.0/js/uikit.min.js"></script>
<script type="text/javascript" src="uikit-2.8.0/js/addons/notify.min.js"></script>
<script type="text/javascript">
	(function(window,$){
		var kakaka={
			url:"",
			init:function(){
				kakaka.url="${ctx}";
				$.UIkit.notify("页面初始化完成", {status:"info",timeout:500});
				$("#btnGet").click(kakaka.get);
				$("#btnAdd").click(kakaka.add);
				$("#btnDel").click(kakaka.del);
				$("#btnUpdate").click(kakaka.update);
				$("#btnList").click(kakaka.list);
			},
			get:function(){
				$.ajax({
					url: kakaka.url +person/101/',
					type:"GET",
				        dataType:"json",
					success : function(data) {
		                $('#result').html(data.name + " , " + data.sex+ " , " +data.age);
		            }
				}).done(function(data, status, xhr) {
					$.UIkit.notify(data.msg, {status:"success",timeout:1000});
				}).fail(function(xhr, status, error) {
					$.UIkit.notify("请求失败!", {status:"danger",timeout:2000});
				});
			},
			add:function(){
				$.ajax({
					url: kakaka.url +"person",
					type:"POST",
					dataType:"json",
					data: {id: 1,name:"张三",sex:"男",age:23}
				}).done(function(data, status, xhr) {
					$.UIkit.notify(data.msg, {status:"success",timeout:1000});
				}).fail(function(xhr, status, error) {
					$.UIkit.notify("请求失败!", {status:"danger",timeout:2000});
				});
			},
			del:function(){
				$.ajax({
					url: kakaka.url +"person/109",
					type:"DELETE",
					dataType:"json"
				}).done(function(data, status, xhr) {
					$.UIkit.notify(data.msg, {status:"success",timeout:1000});
				}).fail(function(xhr, status, error) {
					$.UIkit.notify("请求失败!", {status:"danger",timeout:2000});
				});
			},
			update:function(){
				$.ajax({
					url: kakaka.url +"person",
					type:"PUT",//注意在传参数时,加:_method:"PUT" 将对应后台的PUT请求方法
					dataType:"json",
					data:  {id: 221,name:"王五",sex:"男",age:23}
				}).done(function(data, status, xhr) {
					$.UIkit.notify(data.msg, {status:"success",timeout:1000});
				}).fail(function(xhr, status, error) {
					$.UIkit.notify("请求失败!", {status:"danger",timeout:2000});
				});
			},
			list:function(){
				$.ajax({
					url: kakaka.url +"person",
					contentType: "application/x-www-form-urlencoded; charset=utf-8",
					type:"PATCH", 
					dataType:"json",
					data: {_method:"PATCH",name:"王五"}
				}).done(function(data, status, xhr) {
					$.UIkit.notify("查询人员信息成功", {status:"success",timeout:1000});
				}).fail(function(xhr, status, error) {
					$.UIkit.notify("请求失败!", {status:"danger",timeout:2000});
				});
			}
		};
		window.kakaka=(window.kakaka)?window.kakaka:kakaka;
		$(function(){
			kakaka.init();
		});
	})(window,jQuery);
</script>
</body>
</html>


转载于:https://my.oschina.net/youway/blog/306433

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值