spring mvc (six) implement REST interface GET/POST/PUT/DELETE

Implement restful-style api interface based on springmvc.

1.Restful
Restful-style interface abstracts functions into resource path mappings, which are accessed in the form of HTTP GET /resource/{id}. Mainly divided into the following types of interfaces:
address request method illustrate
/resources GET Get all resources
/resources POST Create a new resource, the content contains the resource content
/resource/{id} GET Get the resource with the id number
/resource/{id} PUT Update the resource numbered id, the content contains the resource content
/resource/{id} DELETE delete resource with id

{id} is called a path variable, which tells restful which resource you want to check, modify, and delete.
The interface generally returns data in json/xml format, which is convenient for server programs and browser scripts to call the interface and process the returned data.
According to the Restful style, the teacher module is designed as two resource addresses: /restMvc/teachers and /restMvc/teachers/{id}.
The basic spring configuration, springmvc configuration, and the implementation of the object interface of each layer are shown in the previous sections.

2./teachers
Create a new TeachersMvcResource resource class:
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;
	}

}

The @Controller and @RequestMapping("/restMvc/teachers") annotations in the class declare that this class is a Controller class and is bound to the /restMvc/teachers address, @RequestMapping(method = { RequestMethod.GET }) and @ The RequestMapping(method = { RequestMethod.POST }) annotation responds to GET and POST requests respectively, and the parameters in the Contentbody will be automatically encapsulated as Teacher teacher.

3./teacher/{id}
adds a new TeacherMvcResource class:
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());
		// If there is no id attribute in the teacher, it needs to be set separately
		// 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;
	}

}

Bind the service to the /restMvc/teacher/{id} address in the class, @RequestMapping(method = { RequestMethod.GET }), @RequestMapping(method = { RequestMethod.PUT }) and @RequestMapping(method = { RequestMethod }) .DELETE }) annotation responds to GET, PUT and POST requests respectively, @PathVariable("id") Integer id receives {id} path variable.

4. The test
rest interface can be accessed using the server program (URL, HttpClient library), js (jquery ajax). Here is a simple and practical browser plug-in to test.
Use FireFox's HttpRquester plugin to access the interface:
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. Use the server program to access the rest
and use the HttpClient library to test the rest interface. The code of the test class TestRestMvc is as follows:
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":[]}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326681281&siteId=291194637