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.输入端点 ...
随机推荐
- 在java中如何在非servlet的普通类中获取request、response、session
原文:http://blog.csdn.net/u012255097/article/details/53092628 在spring的普通类中: HttpServletRequest request ...
- Shiro+SpringMVC 实现更安全的登录(加密匹配&登录失败超次数锁定帐号)
原文:http://blog.csdn.net/wlwlwlwl015/article/details/48518003 前言 初学shiro,shiro提供了一系列安全相关的解决方案,根据官方的介绍 ...
- iOS开发笔记_4自定义TabBar
新博客:http://www.liuchendi.com 好多APP都使用的是自定义的TabBar,那这个功能应该如何实现呢?首先应该解决的问题就是,加载NavigationController的时候 ...
- fullPage全屏滚动的实现
fullPage.js 是一个基于 jQuery 的插件,它能够很方便.很轻松的制作出全屏网站. 用法: 1.引入jquery 2.引入fullPage 3.每个section代表一屏 4.js启动: ...
- 关于 modelNameLike 查询无数据
---恢复内容开始--- 1.今天在测试的时候发现 model中的name不能模糊查询. ModelQuery modelQuery = repositoryService.createModelQu ...
- ylbtech-LanguageSamples-ConditionalMethods(条件方法)
ylbtech-Microsoft-CSharpSamples:ylbtech-LanguageSamples-ConditionalMethods(条件方法) 1.A,示例(Sample) 返回顶部 ...
- http://www.ablanxue.com/shtml/201411/25904_1.shtml
http://www.ablanxue.com/shtml/201411/25904_1.shtml
- Hello Ragel -- 生成状态机的神器
Ragel 是个很 NB 的能生成状态机的编译器,而且支持一堆语言:C.C++.Object-C.C#.D.Java.Go 以及 Ruby. 原来的文本解析器是用正则表达式实现的,随着状态(if-el ...
- HTML5 Canvas 绘制库存变化折线 计算出库存周转率
<!DOCTYPE html> <html lang="utf-8"> <meta http-equiv="Content-Type&quo ...
- 高仿手机QQ音乐之——Android带进度条的开关
最新版的手机QQ音乐体验确实不错,发现首页播放按钮能够显示歌曲当前进度条.认为挺有新意.效果例如以下: 自己琢磨了下.能够用自己定义组件来实现,试着做了一下.效果例如以下: 整理了下思路.大概设计流程 ...