`
sb33060418
  • 浏览: 152076 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

spring mvc(六)实现REST接口GET/POST/PUT/DELETE

阅读更多
基于springmvc实现restful样式的api接口。

1.Restful
Restful样式的接口将功能抽象为资源resource路径映射,以HTTP GET /resource/{id} 的方式访问。主要分为以下几类接口:
地址请求方法说明
/resourcesGET获取所有资源
/resourcesPOST创建新资源,content中包含资源内容
/resource/{id}GET获取编号为id的资源
/resource/{id}PUT更新编号为id的资源,content中包含资源内容
/resource/{id}DELETE删除编号为id的资源

{id}称为路径变量,告诉restful你要对哪个资源进行查、改、删。
接口一般返回json/xml格式数据,方便服务端程序、浏览器脚本调用接口并处理返回数据。
按照Restful样式,teacher模块设计为两个资源地址:/restMvc/teachers和/restMvc/teachers/{id}。
基础的spring配置、springmvc配置、各层对象接口实现见前几节内容。

2./teachers
新建TeachersMvcResource资源类:
package com.sunbin.test.restMvc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;

import com.sunbin.test.teacher.pojo.Teacher;
import com.sunbin.test.teacher.service.TeacherService;

@Controller
@RequestMapping("/restMvc/teachers")
public class TeachersMvcResource {

	@Autowired
	private TeacherService teacherService;

	@RequestMapping(method = { RequestMethod.GET })
	public ModelAndView get(HttpServletRequest arg0, HttpServletResponse arg1)
			throws Exception {
		System.out.println("RestMvc TeachersResource.get");
		ModelAndView modelAndView = new ModelAndView(
				new MappingJackson2JsonView());
		modelAndView.addObject("teachers", teacherService.list());
		return modelAndView;
	}

	@RequestMapping(method = { RequestMethod.POST })
	public ModelAndView post(Teacher teacher, HttpServletRequest arg0,
			HttpServletResponse arg1) throws Exception {
		ModelAndView modelAndView = new ModelAndView(
				new MappingJackson2JsonView());
		System.out.println("RestMvc TeachersResource.post:" + teacher);
		teacherService.save(teacher);
		modelAndView.addObject("status", "y");
		return modelAndView;
	}

}

类中@Controller和@RequestMapping("/restMvc/teachers")注解声明了此类是Controller类并绑定到/restMvc/teachers地址,两个方法的@RequestMapping(method = { RequestMethod.GET })和@RequestMapping(method = { RequestMethod.POST })注解分别响应GET和POST请求,Contentbody里面的参数会被自动封装成Teacher teacher。

3./teacher/{id}
新增TeacherMvcResource类:
package com.sunbin.test.restMvc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;

import com.sunbin.test.teacher.pojo.Teacher;
import com.sunbin.test.teacher.service.TeacherService;

@Controller
@RequestMapping("/restMvc/teacher/{id}")
public class TeacherMvcResource {

	@Autowired
	private TeacherService teacherService;

	@RequestMapping(method = { RequestMethod.GET })
	public ModelAndView get(@PathVariable("id") Integer id,
			HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
		System.out.println("RestMvc TeacherResource.get:" + id);
		ModelAndView modelAndView = new ModelAndView(
				new MappingJackson2JsonView());
		Teacher teacher = new Teacher();
		teacher.setId(id);
		modelAndView.addObject("teacher", teacherService.get(teacher));
		return modelAndView;
	}

	@RequestMapping(method = { RequestMethod.PUT })
	public ModelAndView put(@PathVariable("id") Integer id, Teacher teacher,
			HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
		ModelAndView modelAndView = new ModelAndView(
				new MappingJackson2JsonView());
		// 如果teacher中不含id属性,需要单独设置
		// teacher.setId(id);
		System.out.println("RestMvc TeacherResource.put:" + id + ":" + teacher);
		teacherService.update(teacher);
		modelAndView.addObject("status", "y");
		return modelAndView;
	}

	@RequestMapping(method = { RequestMethod.DELETE })
	public ModelAndView delete(@PathVariable("id") Integer id,
			HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
		ModelAndView modelAndView = new ModelAndView(
				new MappingJackson2JsonView());
		Teacher teacher = new Teacher();
		teacher.setId(id);
		System.out.println("RestMvc TeacherResource.delete:" + id);
		teacherService.remove(teacher);
		modelAndView.addObject("status", "y");
		return modelAndView;
	}

}

类中将服务绑定到/restMvc/teacher/{id}地址,方法的@RequestMapping(method = { RequestMethod.GET })、@RequestMapping(method = { RequestMethod.PUT })和@RequestMapping(method = { RequestMethod.DELETE })注解分别响应GET、PUT和POST请求,@PathVariable("id") Integer id接收{id}路径变量。

4.测试
rest接口可以使用服务端程序(URL、HttpClient库)、js(jquery ajax)进行访问。这里简单实用浏览器插件来测试。
使用FireFox的HttpRquester插件访问接口:
POST
POST http://localhost:8080/testRest/restMvc/teachers
Content-Type: application/x-www-form-urlencoded
name=a&age=1
-- response --
200 OK
Server:  Apache-Coyote/1.1
Pragma:  no-cache
Cache-Control:  no-cache, no-store, max-age=0
Expires:  Thu, 01 Jan 1970 00:00:00 GMT
Content-Type:  application/json;charset=UTF-8
Content-Language:  zh-CN
Transfer-Encoding:  chunked
Date:  Tue, 23 May 2017 02:31:56 GMT

{"teacher":{"id":1,"age":1,"name":"a"},"status":"y"}

GET
GET http://localhost:8080/testRest/restMvc/teachers

-- response --
200 OK
Server:  Apache-Coyote/1.1
Pragma:  no-cache
Cache-Control:  no-cache, no-store, max-age=0
Expires:  Thu, 01 Jan 1970 00:00:00 GMT
Content-Type:  application/json;charset=UTF-8
Content-Language:  zh-CN
Transfer-Encoding:  chunked
Date:  Tue, 23 May 2017 02:36:16 GMT

{"teachers":[{"id":1,"age":1,"name":"a"}]}

PUT
PUT http://localhost:8080/testRest/restMvc/teacher/1
Content-Type: application/x-www-form-urlencoded
name=b&age=2
-- response --
200 OK
Server:  Apache-Coyote/1.1
Pragma:  no-cache
Cache-Control:  no-cache, no-store, max-age=0
Expires:  Thu, 01 Jan 1970 00:00:00 GMT
Content-Type:  application/json;charset=UTF-8
Content-Language:  zh-CN
Transfer-Encoding:  chunked
Date:  Tue, 23 May 2017 02:37:41 GMT

{"teacher":{"id":1,"age":2,"name":"b"},"status":"y"}

GET
GET http://localhost:8080/testRest/restMvc/teacher/1

-- response --
200 OK
Server:  Apache-Coyote/1.1
Pragma:  no-cache
Cache-Control:  no-cache, no-store, max-age=0
Expires:  Thu, 01 Jan 1970 00:00:00 GMT
Content-Type:  application/json;charset=UTF-8
Content-Language:  zh-CN
Transfer-Encoding:  chunked
Date:  Tue, 23 May 2017 02:38:29 GMT

{"teacher":{"id":1,"age":2,"name":"b"}}

DELETE
DELETE http://localhost:8080/testRest/restMvc/teacher/1

-- response --
200 OK
Server:  Apache-Coyote/1.1
Pragma:  no-cache
Cache-Control:  no-cache, no-store, max-age=0
Expires:  Thu, 01 Jan 1970 00:00:00 GMT
Content-Type:  application/json;charset=UTF-8
Content-Language:  zh-CN
Transfer-Encoding:  chunked
Date:  Tue, 23 May 2017 02:38:46 GMT

{"status":"y"}

5.使用服务器程序访问rest
使用HttpClient库对rest接口进行测试,测试类TestRestMvc代码如下:
package com.sunbin.test.restMvc;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class TestRestMvc {

	public static final String URL_BASE = "http://localhost:8080/testRest/restMvc/";

	public static void main(String[] args) throws ParseException,
			ClientProtocolException, IOException {
		String module = "teacher";
		String url = "";
		DefaultHttpClient client = new DefaultHttpClient();
		HttpEntity entity = null;
		String result = "";
		Map map = null;
		HttpGet httpGet = null;
		HttpPost httpPost = null;
		HttpPut httpPut = null;
		HttpDelete httpDelete = null;

		url = URL_BASE + module + "s";
		System.out.println("get\t " + url);
		httpGet = new HttpGet(url);
		result = EntityUtils.toString(client.execute(httpGet).getEntity());
		System.out.println(result);

		url = URL_BASE + module + "s";
		System.out.println("post\t " + url);
		httpPost = new HttpPost(url);
		map = new HashMap();
		map.put("name", "a");
		map.put("age", "1");
		entity = new UrlEncodedFormEntity(getParam(map), "UTF-8");
		httpPost.setEntity(entity);
		result = EntityUtils.toString(client.execute(httpPost).getEntity());
		System.out.println(result);

		url = URL_BASE + module + "s";
		System.out.println("get\t " + url);
		httpGet = new HttpGet(url);
		result = EntityUtils.toString(client.execute(httpGet).getEntity());
		System.out.println(result);

		url = URL_BASE + module + "/1";
		System.out.println("get\t " + url);
		httpGet = new HttpGet(url);
		result = EntityUtils.toString(client.execute(httpGet).getEntity());
		System.out.println(result);

		url = URL_BASE + module + "/1";
		System.out.println("put\t " + url);
		httpPut = new HttpPut(url);
		map = new HashMap();
		map.put("name", "aa");
		map.put("age", "11");
		entity = new UrlEncodedFormEntity(getParam(map), "UTF-8");
		httpPut.setEntity(entity);
		result = EntityUtils.toString(client.execute(httpPut).getEntity());
		System.out.println(result);

		url = URL_BASE + module + "s";
		System.out.println("get\t " + url);
		httpGet = new HttpGet(url);
		result = EntityUtils.toString(client.execute(httpGet).getEntity());
		System.out.println(result);

		url = URL_BASE + module + "/1";
		System.out.println("delete\t " + url);
		httpDelete = new HttpDelete(url);
		result = EntityUtils.toString(client.execute(httpDelete).getEntity());
		System.out.println(result);

		url = URL_BASE + module + "s";
		System.out.println("get\t " + url);
		httpGet = new HttpGet(url);
		result = EntityUtils.toString(client.execute(httpGet).getEntity());
		System.out.println(result);

	}

	public static List<NameValuePair> getParam(Map parameterMap) {
		List<NameValuePair> param = new ArrayList<NameValuePair>();
		Iterator it = parameterMap.entrySet().iterator();
		while (it.hasNext()) {
			Entry parmEntry = (Entry) it.next();
			param.add(new BasicNameValuePair((String) parmEntry.getKey(),
					(String) parmEntry.getValue()));
		}
		return param;
	}
}

输出结果如下:
get http://localhost:8080/testRest/restMvc/teachers
{"teachers":[]}
post http://localhost:8080/testRest/restMvc/teachers
{"teacher":{"id":1,"age":1,"name":"a"},"status":"y"}
get http://localhost:8080/testRest/restMvc/teachers
{"teachers":[{"id":1,"age":1,"name":"a"}]}
get http://localhost:8080/testRest/restMvc/teacher/1
{"teacher":{"id":1,"age":1,"name":"a"}}
put http://localhost:8080/testRest/restMvc/teacher/1
{"teacher":{"id":1,"age":11,"name":"aa"},"status":"y"}
get http://localhost:8080/testRest/restMvc/teachers
{"teachers":[{"id":1,"age":11,"name":"aa"}]}
delete http://localhost:8080/testRest/restMvc/teacher/1
{"status":"y"}
get http://localhost:8080/testRest/restMvc/teachers
{"teachers":[]}
分享到:
评论

相关推荐

    Spring MVC REST Demo

    "Spring MVC REST Demo"是一个示例项目,旨在展示如何在Spring MVC框架中实现RESTful Web服务。下面将详细讨论Spring MVC与RESTful API的结合,以及如何创建和测试此类服务。 首先,Spring MVC是Spring框架的一部分...

    spring 3.0 mvc实现rest代码

    REST(Representational State Transfer)是一种架构风格,常用于设计网络应用程序,强调通过统一资源标识符(URI)来访问资源,并通过标准的 HTTP 方法(如 GET、POST、PUT、DELETE)来操作这些资源。Spring MVC 是...

    spring mvc rest 小例子

    在这个小例子中,我们将探讨如何使用Spring MVC来实现REST接口。 首先,让我们理解Spring MVC的基本架构。Spring MVC通过DispatcherServlet作为前端控制器,接收HTTP请求,然后根据请求映射找到相应的Controller...

    spring mvc rest基础学习demo

    - `@GetMapping`、`@PostMapping`、`@PutMapping`、`@DeleteMapping`分别用于处理HTTP的GET、POST、PUT、DELETE请求。 3. **处理请求和响应** - `@RequestParam`注解用于从URL参数中获取值。 - `@PathVariable`...

    Spring MVC – Easy REST-Based JSON Services with @ResponseBody

    在RESTful服务中,URL代表资源,HTTP方法(GET、POST、PUT、DELETE等)代表对这些资源的操作。 创建RESTful JSON服务时,我们首先需要配置Spring MVC的DispatcherServlet,它是Spring MVC的核心组件,负责处理HTTP...

    spring3.0 mvc和rest入门例子

    3. **RESTful服务**:REST(Representational State Transfer)是一种网络应用程序的设计风格和开发方式,基于HTTP协议,以资源为中心,使用标准HTTP方法(GET、POST、PUT、DELETE等)进行操作。Spring 3.0引入了对...

    httpclient 4.5 相关jar包 (Spring mvc REST风格对外接口,HttpClient调用)

    这个库为开发者提供了强大的功能,能够构建复杂的网络交互,比如GET、POST、PUT、DELETE等HTTP方法的调用。这里我们关注的是HTTPClient 4.5版本,以及与Spring MVC REST风格接口的集成。在"Spring mvc REST风格对外...

    Spring MVC 4.2.3

    3. **RESTful支持**:Spring MVC提供了对RESTful风格的HTTP方法(如GET、POST、PUT、DELETE等)的优秀支持,便于构建符合REST原则的Web服务。 4. **ModelAndView对象的改进**:此版本对`ModelAndView`对象进行了...

    spring_MVC源码

    本文主要介绍使用注解方式配置的spring mvc,之前写的spring3.0 mvc和rest小例子没有介绍到数据层的内容,现在这一篇补上。下面开始贴代码。 文中用的框架版本:spring 3,hibernate 3,没有的,自己上网下。 先说...

    spring-rest.rar_DEMO_employeeDS.java_rest spring mvc_spring mvc_

    在本示例中,我们将深入探讨如何利用Spring MVC框架构建RESTful API,主要涉及`employeeDS.java`这个可能的数据服务类以及与`rest_spring_mvc`、`spring_mvc`和`spring_rest`相关的概念。`spring-rest.rar`是一个...

    spring mvc restful service

    RESTful服务通常使用HTTP动词(GET、POST、PUT、DELETE等)来表示对资源的操作。 2. **Spring MVC与REST**:Spring MVC提供了一套优雅的方式来实现RESTful服务。通过使用`@RestController`注解,我们可以创建处理...

    基于Spring和Spring MVC实现可跨域访问的REST服务

    REST服务通常以JSON或XML格式提供数据,使用HTTP方法(GET、POST、PUT、DELETE等)进行操作。 在Spring MVC中,我们可以通过定义Controller类来创建REST端点。这些类包含处理HTTP请求的方法,通常用`@...

    使用Spring MVC 搭建Rest服务.doc

    2. **HTTP方法**:GET、POST、PUT、DELETE等HTTP方法对应REST服务中的CRUD操作。GET用于获取资源,POST用于创建资源,PUT用于更新资源,DELETE用于删除资源。 3. **状态码**:HTTP状态码是服务器对请求的响应,如...

    SPRING-MVC-MQ-CXF-REST_Demo

    REST(Representational State Transfer)是一种网络应用程序的设计风格和开发方式,基于HTTP协议,强调资源的概念,通过URI(Uniform Resource Identifier)定位资源,通过HTTP方法(GET、POST、PUT、DELETE等)...

    spring mvc

    12. **RESTful风格**: Spring MVC 支持创建RESTful API,通过@RequestMapping配合HTTP动词(GET、POST、PUT、DELETE等),可以轻松构建符合REST原则的接口。 13. **异常处理**: 通过@ControllerAdvice和@...

    Spring MVC Cookbook(PACKT,2016).pdf

    7. **RESTful服务**:创建符合REST原则的URL结构,使用HTTP动词(GET、POST、PUT、DELETE)来实现CRUD操作,并使用JSON或XML进行数据交换。 8. **异常处理**:了解如何自定义异常处理器,以及使用@ControllerAdvice...

    精通spring mvc 4 看透springmvc pdf 高清完全版

    书中详细介绍了如何定义RESTful资源,使用HTTP动词(GET、POST、PUT、DELETE等)处理操作,以及如何处理JSON和XML数据格式。 在实战部分,本书提供了丰富的案例和示例代码,让读者能够在实践中学习和应用所学知识。...

    第四章 Spring MVC Rest风格的url、静态资源标签

    REST(Representational State Transfer)是一种软件架构风格,常用于Web服务设计,它强调通过HTTP方法(如GET、POST、PUT、DELETE等)来操作资源。Spring MVC提供了强大的支持来实现RESTful API。 首先,让我们...

    Spring3.0实现REST实例

    2. **统一接口**:REST服务通过HTTP方法(GET、POST、PUT、DELETE等)与资源交互。 3. **缓存机制**:客户端可以缓存响应,提高性能。 4. **分层系统**:中间层可以添加额外的安全性和功能,而不会影响客户端和...

    Spring3 MVC REST + JPA2 (Hibernate 3.6.1) 构建投票系统 - 2.Spring MVC REST

    RESTful API 使用 HTTP 方法(如 GET、POST、PUT、DELETE)来操作资源,实现无状态、缓存、统一接口等原则。在本项目中,Spring MVC 被用来创建 RESTful API,使得客户端可以通过简单的 HTTP 请求与投票系统交互。 ...

Global site tag (gtag.js) - Google Analytics