第 4 章 RestTemplate - Spring4 Restful

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
云数据库 MongoDB,通用型 2核4GB
简介:

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

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

4.1. RestTemplate Example

4.1.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>		
			
			

4.1.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>		
			
			

4.1.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>
			
			

4.1.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;
	}	
}
			
			

4.1.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 + "]";
	}

}
			
			

4.1.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"}	
			
			



原文出处:Netkiller 系列 手札
本文作者:陈景峯
转载请与作者联系,同时请务必标明文章原始出处和作者信息及本声明。

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
目录
相关文章
|
4月前
|
前端开发 Java API
6:RestFul API-Java Spring
6:RestFul API-Java Spring
130 0
|
1月前
|
Java API Maven
使用Java和Spring Boot构建RESTful API
使用Java和Spring Boot构建RESTful API
16 0
|
3月前
|
JSON 前端开发 Java
Spring MVC响应结合RESTful风格开发,打造具有强大功能和良好体验的Web应用!
Spring MVC响应结合RESTful风格开发,打造具有强大功能和良好体验的Web应用!
|
4月前
|
缓存 Java 关系型数据库
Spring Boot实现RESTful接口架构实战(包括REST的讲解、定义、REST服务测试)
Spring Boot实现RESTful接口架构实战(包括REST的讲解、定义、REST服务测试)
52 0
|
5月前
|
设计模式 Java API
使用Spring框架创建一个RESTful API,实现学生信息的管理,包括资源的创建、读取、更新和删除。
在当今的Web应用程序开发中,RESTful API(Representational State Transferful Application Programming Interface)变得越来越重要。Spring框架提供了强大的工具和功能,以便轻松创建、读取、更新和删除(CRUD)资源。在这篇文章中,我们将深入探讨如何使用Spring框架创建一个RESTful API,并通过一个完整的示例演示。
|
5月前
|
前端开发 Java API
什么是RESTful API,Spring MVC如何支持RESTful架构
RESTful API(Representational State Transfer)是一种基于HTTP协议的软件架构风格,用于设计网络应用程序的API。它强调使用标准的HTTP方法(GET、POST、PUT、DELETE等)来进行资源的操作,以及使用URI来标识资源。RESTful API的设计目标是简单、可扩展、易于理解和使用。
BXA
|
11月前
|
JSON 前端开发 安全
基于Spring的RESTful API开发
RESTful API是一种建立在HTTP协议之上的Web API。它遵循REST设计规范使用HTTP请求通过网络进行通信,实现对资源的增、删、改、查等操作。RESTful API与传统的Web API相比更具有灵活性、可扩展性与可维护性,已经成为现代Web服务的首选技术之一。
BXA
88 0
|
6月前
|
前端开发 Java API
# Spring MVC与RESTful API:如何设计高效的Web接口
# Spring MVC与RESTful API:如何设计高效的Web接口
57 0
|
8月前
|
JSON Java 数据库
Spring Data JPA构建Restful服务应用Demo
昨天介绍了什么是Rest和Restful,没有看到的同学可以参考我的这篇文章:深入理解REST与RESTfulAPI 那么说了这么多咱就实战一把,如何用SpringBoot来实现Rest,只需要Spring DataJPA和Spring Data Rest两个依赖包,快速开发一个restful应用。
157 1
|
8月前
|
Java 测试技术 API
Spring Boot之Restful服务与Swagger框架:构建易用的API文档与测试工具
本篇详细介绍了如何在Spring Boot应用中构建Restful服务,并结合Swagger框架实现自动生成API文档和提供API测试工具的方法。通过编写Controller类定义Restful API,以及配置Swagger框架,读者可以轻松地生成API文档和进行API测试,从而提升开发效率和项目可维护性。该博文帮助读者了解了如何使用Spring Boot和Swagger框架来简化API文档编写和测试的过程,为Web应用开发提供了有力的支持。
206 2
Spring Boot之Restful服务与Swagger框架:构建易用的API文档与测试工具