Spring4 MVC REST服务使用@RestController实例
- Spring 4.0.6.RELEASE
- jackson-mapper-asl 1.9.13
- Maven 3
- JDK 1.6
- Tomcat 7.0.54
- Eclipse JUNO Service Release 2
让我们现在开始!

<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion>
<groupId>com.yiibai.springmvc</groupId>
<artifactId>Spring4MVCRestServiceDemo</artifactId>
<packaging>war</packaging>
<version>1.0.0</version>
<name>Spring4MVCRestServiceDemo Maven Webapp</name> <properties>
<springframework.version>4.0.6.RELEASE</springframework.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency> <dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency> <dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<warName>Spring4MVCRestServiceDemo</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<finalName>Spring4MVCRestServiceDemo</finalName>
</build>
</project>
上面的 pom.xml 与以前的教程中定义的相同。有一个显着的区别: 我们已经包括一个依赖于Jackson 库(jackson-mapper-asl),其将用于所述响应数据转换成JSON字符串。
对于Spring 4.1.x 和以上, jackson-databind 2.3或以上是推荐使用的,以避免转换问题。
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
package com.yiibai.springmvc.domain;
public class Message {
String name;
String text;
public Message(String name, String text) {
this.name = name;
this.text = text;
}
public String getName() {
return name;
}
public String getText() {
return text;
}
}
package com.yiibai.springmvc.controller; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import com.yiibai.springmvc.domain.Message; @RestController
public class HelloWorldRestController { @RequestMapping("/hello/{player}")
public Message message(@PathVariable String player) { Message msg = new Message(player, "Hello " + player);
return msg;
} }
@PathVariable表示参数将被绑定到变量 URI 模板。更有趣的事情,这里要注意的是,这里我们使用的是 @RestController 注解,这标志着这个类作为控制器,每一个方法返回域对象/pojo代替一个视图。这意味着我们不再使用视图解析器,我们不再直接发送响应的HTML,我们只发送的域对象转换成格式。在我们的例子中,由于 jackson 包含在类路径中,消息对象将转换成JSON格式。
package com.yiibai.springmvc.configuration; import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc; @Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.yiibai.springmvc")
public class HelloWorldConfiguration { }
在这里,这个类是主要提供组件,扫描和注释支持。需要注意的是,我们没有任何视图解析器配置,因为我们在Rest案例并不需要。
添加一个初始化类实现WebApplicationInitializer在src/main/java,使用如下图所示指定包(在这种情况下,替代在web.xml中定义的任何spring的配置)。在Servlet 3.0容器启动时,这个类会被加载并实例,它是在启动时方法将通过servlet容器调用。
package com.yiibai.springmvc.configuration; import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration; import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet; public class HelloWorldInitializer implements WebApplicationInitializer { public void onStartup(ServletContext container) throws ServletException { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(HelloWorldConfiguration.class);
ctx.setServletContext(container); ServletRegistration.Dynamic servlet = container.addServlet(
"dispatcher", new DispatcherServlet(ctx)); servlet.setLoadOnStartup(1);
servlet.addMapping("/");
} }
更新:请注意,上面的类可以写成更加简洁[和它的首选方式],通过扩展 AbstractAnnotationConfigDispatcherServletInitializer 基类,如下所示:
package com.yiibai.springmvc.configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class HelloWorldInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { HelloWorldConfiguration.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
现在构建 war(在 Eclipse中)或通过 Maven 命令行( mvn clean install)。 部署 war 文件到Servlet3.0容器。


就这样,所有输出如上所示。
现在,如上面提到的,只是通过增加模型类(Message)JAXB注释,我们可以让XML输出支持以及JSON输出。下面是相同的演示:
package com.yiibai.springmvc.domain; import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "pizza")
public class Message { String name;
String text; public Message(){ } public Message(String name, String text) {
this.name = name;
this.text = text;
} @XmlElement
public String getName() {
return name;
} @XmlElement
public String getText() {
return text;
} }

再次访问:http://localhost:8080/Spring4MVCRestServiceDemo/hello/Yiibai.json


到这里,全部完成!
Spring4 MVC REST服务使用@RestController实例的更多相关文章
- REST服务使用@RestController实例,输出xml/json
REST服务使用@RestController实例,输出xml/json 需要用到的服务注解 org.springframework.web.bind.annotation.RestControlle ...
- Spring4 MVC HelloWorld 注解和JavaConfig实例
在这一节中,我们以 Spring4 MVC HelloWorld 注释/JavaConfig为示例,一步一步以简单的方式学习Spring4 MVC 的注解,项目设置,代码,部署和运行. 在先前的 Sp ...
- Spring4 MVC+ AngularJS CRUD使用$http实例
这篇文章显示了使用Spring MVC4整合AngularJS.我们将创建一个使用后端和AngularJS作为前端的纯JSP封装Spring REST API一个CRUD应用程序, 使用 $http ...
- Spring4 MVC ContentNegotiatingViewResolver多种输出格式实例
本文演示支持多种输出格式,这里 Spring4 MVC应用程序使用了 Spring ContentNegotiatingViewResolver .我们将生成应用程序输出XML,JSON,PDF,XL ...
- Spring4 MVC ContentNegotiatingViewResolver多种输出格式实
前段时间在一个项目里面发现,针对Excel的处理没有一个公用的视图,来个下载的需求就要自己去写一堆POI的东西,终于有一天给我也来了几个,还是按照以前的方式来写,写多了真心想吐,后面想想还是有必要整个 ...
- ASP.NET Core MVC 2.x 全面教程_ASP.NET Core MVC 03. 服务注册和管道
ASP.NET Core MVC 2.x 全面教程_ASP.NET Core MVC 03. 服务注册和管道 语雀: https://www.yuque.com/yuejiangliu/dotnet/ ...
- Spring4 MVC Hibernate4集成 Annotation
Spring4 MVC Hibernate4集成 Annotation 一.本文所用环境 二.工程目录 三.Maven添加依赖 四.新建数据库表 五.配置文件 六.Model层 七.DAO层 八.Se ...
- Spring4 MVC Hibernate4集成
Spring4 MVC Hibernate4集成 一. 本文所用环境 Spring4.0.3.RELEASE Hibernate4.3.5.Final Mysql 二. 工程目录 三. ...
- Azure 云服务中的实例端点
Azure云服务(cloud Servive)中有三种端点类型(endpoint type):输入端点(input);内部端点(internal);实例端点(InstanceInput) 1.输入端点 ...
随机推荐
- Vmware+Virtualbox+Ubuntu+debian+USB转串口+kermit
当前的环境是:在Win7笔记本主机上安装VirtualBox+Ubuntu12_04,串口使用USB转串口 如果使用的虚拟机是VirtualBox: 如果使用的虚拟机是Vmware: 执行这步后,主机 ...
- SpringBoot拦截器中service或者redis注入为空的问题
原文:https://my.oschina.net/u/1790105/blog/1490098 这两天遇到SpringBoot拦截器中Bean无法注入问题.下面介绍我的思考过程和解决过程: 1.由于 ...
- 微信 JS SDK 的 chooseImage 接口在部分安卓机上容易造成页面刷新
该问题的症状是,当调用 chooseImage 接口并选择拍照,选择照片确定之后,然后从相机返回后,当前web页面就刷新了一次,导致拍照的图片无法选择上传:但是如果直接从相册中选择图片,则不会出现这个 ...
- 第三天 ThinkPHP手把手高速拼接站点(三)
6月1日,小雨." 梅子金黄杏子肥,麦花雪白菜花稀. 日长篱落无人过,唯有蜻蜓蛱蝶飞." 七.MVC模式 ThinkPHP的MVC开发机制例如以下: M Model层 模型 ...
- IP地址后面斜杠加具体数字详解
其实这种形式就是用CIDR(无类别域间路由选择,Classless and Subnet Address Extensions and Supernetting))的形式表示的一个网段,或者说子网. ...
- [Python爬虫] 之十八:Selenium +phantomjs 利用 pyquery抓取电视之家网数据
一.介绍 本例子用Selenium +phantomjs爬取电视之家(http://www.tvhome.com/news/)的资讯信息,输入给定关键字抓取资讯信息. 给定关键字:数字:融合:电视 抓 ...
- grpc(3):使用 golang 开发 grpc 服务端和client
1,关于grpc-go golang 能够能够做grpc的服务端和client. 官网的文档: http://www.grpc.io/docs/quickstart/go.html https://g ...
- 推荐一个静态页面生成工具-mkdocs
最近需要找一个生成api文档的工具,找来找去发现mkdocs特别符合需求. 部署只需python和pip 直接生成静态html 用markdown编写 不需要再markdown里指明日期.标题等信息 ...
- jsp 页面图片为圆形
直接设置img标签的style属性即可 <img alt="" src="链接地址" style="width: 80px;height: 80 ...
- Python 提取Twitter tweets中的元素(包括text, screen names, hashtags)
CODE: #!/usr/bin/python # -*- coding: utf-8 -*- ''' Created on 2014-7-1 @author: guaguastd @name: ex ...