Spring RestFul and RestTemplate

本文节选自《Netkiller Java 手札》

10.8. Spring4 Restful

@RestController

首先我要禁告各位,Spring发展过程中,每个版本都有一定差异。如果你做实验失败后在网上搜索答案,切记看一下版本号还有文章帖子的发布时间。否则你可能按照Spring3配置方法去Spring4。

@RestController 默认返回 @ResponseBody, 所以@ResponseBody可加可不加

10.8.1. pom.xml

Maven 增加 jackson 开发包

		<dependency>
			<groupId>com.fasterxml.jackson.dataformat</groupId>
			<artifactId>jackson-dataformat-xml</artifactId>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
		</dependency>		

10.8.2. web.xml

url-pattern匹配中增加*.xml跟*.json

	<servlet>
        <servlet-name>springframework</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
   
    <servlet-mapping>
        <servlet-name>springframework</servlet-name>
        <url-pattern>/welcome.jsp</url-pattern>
        <url-pattern>/welcome.html</url-pattern>
        <url-pattern>*.json</url-pattern>
        <url-pattern>*.xml</url-pattern>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>		

10.8.3. springframework.xml

		<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:mongo="http://www.springframework.org/schema/data/mongo" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.5.xsd        
        ">

	<mvc:resources location="/images/" mapping="/images/**" />
	<mvc:resources location="/css/" mapping="/css/**" />
	<mvc:resources location="/js/" mapping="/js/**" />
	<mvc:resources location="/zt/" mapping="/zt/**" />
	<mvc:resources location="/sm/" mapping="/sm/**" />
	<mvc:resources location="/module/" mapping="/module/**" />

	<context:component-scan base-package="cn.netkiller.controller">

	</context:component-scan>
	<context:annotation-config />
	<mvc:annotation-driven />

	<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>


	<bean id="configuracion" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:resources/development.properties" />
	</bean>

	<!-- Redis Connection Factory -->
	<bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:host-name="192.168.2.1" p:port="6379" p:use-pool="true" />

	<!-- redis template definition -->
	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" p:connection-factory-ref="jedisConnFactory" />

	<mongo:db-factory id="mongoDbFactory" host="${mongo.host}" port="${mongo.port}" dbname="${mongo.database}" />
	<!-- username="${mongo.username}" password="${mongo.password}" -->

	<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
		<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
	</bean>

	<mongo:mapping-converter id="converter" db-factory-ref="mongoDbFactory" />
	<bean id="gridFsTemplate" class="org.springframework.data.mongodb.gridfs.GridFsTemplate">
		<constructor-arg ref="mongoDbFactory" />
		<constructor-arg ref="converter" />
	</bean>

</beans>		

10.8.4. RestController

		package cn.netkiller.controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.netkiller.pojo.Message;

@RestController
@RequestMapping("/rest")
public class TestRestController {

	public TrackerRestController() {
		// TODO Auto-generated constructor stub
	}

	@RequestMapping("welcome")
	@ResponseStatus(HttpStatus.OK)
	public String welcome() {
		return "Welcome to RestTemplate Example.";
	}

	@RequestMapping(value = "test", method = RequestMethod.GET, produces = { "application/xml", "application/json" })
	@ResponseStatus(HttpStatus.OK)
	public @ResponseBody Message test(@RequestHeader(value = "accept") String accept) {
		Message message = new Message();
		message.setTitle("test");
		message.setText("Helloworld!!!");
		System.out.println("accept: " + accept);
		System.out.println(message.toString());
		return message;
	}

	@RequestMapping("message/{name}")
	public ResponseEntity<Message> message(@PathVariable String name) {
		Message msg = new Message();
		msg.setTitle(name);
		return new ResponseEntity<Message>(msg, HttpStatus.OK);
	}
	
	@RequestMapping(value = "create", method = RequestMethod.POST, produces = { "application/xml", "application/json" })
	public ResponseEntity<Tracker> create(@RequestBody Tracker tracker) {
		this.mongoTemplate.insert(tracker);
		return new ResponseEntity<Tracker>(tracker, HttpStatus.OK);
	}
	
	@RequestMapping(value = "read", method = RequestMethod.GET, produces = { "application/xml", "application/json" })
	@ResponseStatus(HttpStatus.OK)
	public ArrayList<Tracker> read() {

		ArrayList<Tracker> trackers =  (ArrayList<Tracker>) mongoTemplate.findAll(Tracker.class);
		return trackers;
	}	
}		

10.8.5. POJO

		package cn.netkiller.pojo;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Message {
	
	String title;
    String text;
    
	public Message() {
		// TODO Auto-generated constructor stub
	}
	
	//@XmlElement
	@XmlAttribute  
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	
	//@XmlElement
	@XmlAttribute
	public String getText() {
		return text;
	}
	public void setText(String text) {
		this.text = text;
	}
	@Override
	public String toString() {
		return "Message [title=" + title + ", text=" + text + "]";
	}

}		

10.8.6. 测试

		neo@netkiller:~/www.netkiller.cn$ curl http://172.16.0.1:8080/spring4/rest/welcome.html
Welcome to RestTemplate Example.

neo@netkiller:~/www.netkiller.cn$ curl http://172.16.0.1:8080/spring4/rest/test.json
{"title":"test","text":"Helloworld!!!"}

neo@netkiller:~/www.netkiller.cn$ curl http://172.16.0.1:8080/spring4/rest/test.xml
<Message xmlns=""><title>test</title><text>Helloworld!!!</text></Message>	

neo@netkiller:~/www.netkiller.cn$ curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X POST -d '{"login":"neo", "unique":"356770257607079474","hostname":"www.example.com","referrer":"http://www.netkiller.cn","href":"http://www.netkiller.cn"}' http://172.16.0.1:8080/spring4/rest/create.json
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: application/json
Transfer-Encoding: chunked
Date: Tue, 21 Jun 2016 03:08:26 GMT

{"name":"neo","unique":"356770257607079474","hostname":"www.netkiller.cn","referrer":"http://www.netkiller.cn","href":"http://www.netkiller.cn"}	

10.8.7. RestTemplate

RestTemplate 是 Spring Restful Client 用于调用restful接口

10.8.7.1. GET

	@RequestMapping("/restful/get")
	@ResponseBody
	public String restfulGet() {
		RestTemplate restTemplate = new RestTemplate();
		String text = restTemplate.getForObject("http://inf.netkiller.cn/detail/html/2/2/42564.html", String.class);
		return text;
	}			
10.8.7.1.1. 传递 GET 参数
	@RequestMapping("/restful/get/{id}")
	@ResponseBody
	private static String restfulGetId(@PathVariable String id) {
		final String uri = "http://inf.netkiller.cn/detail/html/{tid}/{cid}/{id}.html";

		Map<String, String> params = new HashMap<String, String>();
		params.put("tid", "2");
		params.put("cid", "2");
		params.put("id", id);
		RestTemplate restTemplate = new RestTemplate();
		String result = restTemplate.getForObject(uri, String.class, params);

		return (result);
	}			

10.8.7.2. POST

	@RequestMapping("/restful/post/{id}")
	@ResponseBody
	private static String restfullPost(@PathVariable String id) {

		final String uri = "http://inf.netkiller.cn/detail/html/{tid}/{cid}/{id}.html";

		Map<String, String> params = new HashMap<String, String>();
		params.put("tid", "2");
		params.put("cid", "2");
		params.put("id", id);

		City city = new City("Shenzhen", "Guangdong");

		RestTemplate restTemplate = new RestTemplate();
		String result = restTemplate.postForObject(uri, city, String.class, params);
		return result;
	}			

10.8.7.3. PUT

	@RequestMapping("/restful/put/{id}")
	private static void restfulPut(@PathVariable String id) {
		final String uri = "http://inf.netkiller.cn/detail/html/{tid}/{cid}/{id}.html";

		Map<String, String> params = new HashMap<String, String>();
		params.put("id", id);

		City city = new City("Shenzhen", "Guangdong");

		RestTemplate restTemplate = new RestTemplate();
		restTemplate.put(uri, city, params);
	}			

10.8.7.4. Delete

	@RequestMapping("/restful/delete/{id}")
	private static void restfulDelete(@PathVariable String id) {
		final String uri = "http://inf.netkiller.cn/detail/html/{tid}/{cid}/{id}.html";

		Map<String, String> params = new HashMap<String, String>();
		params.put("id", id);

		RestTemplate restTemplate = new RestTemplate();
		restTemplate.delete(uri, params);
	}			

10.8.7.5. 在控制器中完整实例

			package api.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import api.domain.City;
import api.repository.CityRepository;

@Controller
public class IndexController {

	@Autowired
	private CityRepository repository;

	// Spring RESTFul Client
	
	@RequestMapping("/restful/get")
	@ResponseBody
	public String restfulGet() {
		RestTemplate restTemplate = new RestTemplate();
		String text = restTemplate.getForObject("http://inf.netkiller.cn/detail/html/2/2/42564.html", String.class);
		return text;
	}

	@RequestMapping("/restful/get/{id}")
	@ResponseBody
	private static String restfulGetId(@PathVariable String id) {
		final String uri = "http://inf.netkiller.cn/detail/html/{tid}/{cid}/{id}.html";

		Map<String, String> params = new HashMap<String, String>();
		params.put("tid", "2");
		params.put("cid", "2");
		params.put("id", id);
		RestTemplate restTemplate = new RestTemplate();
		String result = restTemplate.getForObject(uri, String.class, params);

		return (result);
	}

	@RequestMapping("/restful/post/{id}")
	@ResponseBody
	private static String restfullPost(@PathVariable String id) {

		final String uri = "http://inf.netkiller.cn/detail/html/{tid}/{cid}/{id}.html";

		Map<String, String> params = new HashMap<String, String>();
		params.put("tid", "2");
		params.put("cid", "2");
		params.put("id", id);

		City city = new City("Shenzhen", "Guangdong");

		RestTemplate restTemplate = new RestTemplate();
		String result = restTemplate.postForObject(uri, city, String.class, params);
		return result;
	}

	@RequestMapping("/restful/put/{id}")
	private static void restfulPut(@PathVariable String id) {
		final String uri = "http://inf.netkiller.cn/detail/html/{tid}/{cid}/{id}.html";

		Map<String, String> params = new HashMap<String, String>();
		params.put("id", id);

		City city = new City("Shenzhen", "Guangdong");

		RestTemplate restTemplate = new RestTemplate();
		restTemplate.put(uri, city, params);
	}

	@RequestMapping("/restful/delete/{id}")
	private static void restfulDelete(@PathVariable String id) {
		final String uri = "http://inf.netkiller.cn/detail/html/{tid}/{cid}/{id}.html";

		Map<String, String> params = new HashMap<String, String>();
		params.put("id", id);

		RestTemplate restTemplate = new RestTemplate();
		restTemplate.delete(uri, params);
	}
}

原文发布于微信公众号 - Netkiller(netkiller-ebook)

原文发表时间:2016-08-15

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏DT数据侠

魔都万套短租房数据告诉你,做个短租房东可好?

如果要评选2017年的经济热词,“共享经济”一定当仁不让。这种新的经济模式正以前所未有的速度改变城市商业的原有形态。本文的数据侠范凌、Yaung从短租房的角度入...

1460
来自专栏顶级程序员

小猪佩奇到底有多火?数据和事实告诉你……

豆瓣评分高达9.2,素来挑剔的豆瓣用户可以给这样一部学龄前儿童动画片这么高的评分,足以表明用户对它的认可,说明其质量绝对过硬,要知道此前大火的《熊出没》、《喜洋...

1042
来自专栏全栈数据化营销

数据分析:《三国演义》魏蜀吴联盟深度解析

读三国,就一定要弄清楚国与国、人与人之间的斗争。 三国的历史,就是一部精彩的斗争史,无论是前期的曹袁之争,中期的三国缠斗,还是后期的魏蜀单挑,都充满的了智慧和权...

4468
来自专栏大数据文摘

只有CEO才玩得起的奢侈运动

3458
来自专栏灯塔大数据

原创译文 | 美国禁令后中兴不能再购买高通芯片,美国方面解释原因

转载声明 本文为灯塔大数据原创内容,欢迎个人转载至朋友圈,其他机构转载请在文章开头标注:“转自:灯塔大数据;微信:DTbigdata” 导读:中美贸易战愈演愈烈...

2655
来自专栏养码场

如何边玩狼人杀边撩小姐姐?

752
来自专栏互联资讯

“没有中国茶只有龙德记”为实,“怒掷酒瓶振国威”为虚

1915年巴拿马万国博览会共颁25527个奖!中国拿到了1200多个,茅台只是获得第四等级的奖,其"怒掷酒瓶振国威"故事更是毫无根据的事。

1721
来自专栏PPV课数据科学社区

周末荐影 | 八部电影让你看懂大数据

1 ? 《V客帝国》 在大数据的世界里,V并非指“仇杀”(Vendetta),而是著名的3V定律: Velocity速度——以接近实时的速度处理数据产生报告,而...

3218
来自专栏WeTest质量开放平台团队的专栏

这到底是IT男脱单秘籍,还是一篇双11活动预告

? 从前,小编有一只同事 ? 在业内摸爬滚打五年零两个月,事业有成,技术过人,深受同事喜爱,更被领导器重,距离当上总经理出任CEO迎娶白富美,可能只差一次……...

1181
来自专栏VRPinea

用VR的视角让你看看,灾难和化学武器离我们有多近

37110

扫码关注云+社区