使用Spring MVC 4构建Restful服务

简介:

    使用Spring MVC 4构建RESTful服务相对于其它框架来说,有很多优势。首先,Spring MVC 4作为Spring的框架之一,可以很好地与Spring进行集成。其次,Spring MVC 4的拦截器是在方法层级上的拦截,相对于其它MVC框架(如Struts2)的拦截器具有更高的效率。再者,Spring MVC 4采用基于注解的配置,入手容易,开发灵活。


    Spring MVC 4采用的是jacson解析JSON。jacson一款非常高效强大的JSON工具类,可以轻松地在JAVA对象与json对象和XML文档之间进行序列化和反序列化。本文中的例子采用的是Spring 4.1.1.RELEASE和jacson 2.4.0版本,经测试无任何异常。接下来,上干货:


    开发环境准备:

        Eclipse Luna

        Apache Tomcat 8.0

        JDK 1.7

        Spring 4.1.1.RELEASE

        jackson 2.4.0


    工程目录如下:

wKioL1RmtujyFDVPAAGhvKmuW54452.jpg



    1. 新建Maven Project,选择在“Archetype类型”中,选择“maven-archetype-webapp”。


    2. 在Pom.xml中添加 Maven 依赖,从而可以使用 Spring和jackson中的特性。如果读者使用的是Dynamic Web Project,可以从Maven仓库下载对的Spring Jar和 jacson jar。


    Spring的Maven仓库地址:http://repo1.maven.org/maven2/org/springframework/

    jackson的Maven仓库地址:http://repo1.maven.org/maven2/com/fasterxml/jackson/core/



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
< project  xmlns = "http://maven.apache.org/POM/4.0.0"  xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" >
   < modelVersion >4.0.0</ modelVersion >
   < groupId >com.favccxx.favsoft</ groupId >
   < artifactId >favspringmvcrestful</ artifactId >
   < packaging >war</ packaging >
   < version >0.0.1-SNAPSHOT</ version >
   < name >favspringmvcrestful Maven Webapp</ name >
   < url >http://maven.apache.org</ url >
   
   < properties >
       < spring.version >4.1.1.RELEASE</ spring.version >
       < jackson.version >2.4.0</ jackson.version >
   </ properties >
   
   < dependencies >
     < dependency >
       < groupId >junit</ groupId >
       < artifactId >junit</ artifactId >
       < version >3.8.1</ version >
       < scope >test</ scope >
     </ dependency >
     
     < dependency >
         < groupId >org.springframework</ groupId >
         < artifactId >spring-core</ artifactId >
         < version >${spring.version}</ version >
     </ dependency >
     < dependency >
         < groupId >org.springframework</ groupId >
         < artifactId >spring-webmvc</ artifactId >
         < version >${spring.version}</ version >
     </ dependency >
     < dependency >
         < groupId >org.springframework</ groupId >
         < artifactId >spring-beans</ artifactId >
         < version >${spring.version}</ version >
     </ dependency >
     < dependency >
         < groupId >org.springframework</ groupId >
         < artifactId >spring-context</ artifactId >
         < version >${spring.version}</ version >
     </ dependency >
     
     
     < dependency >
       < groupId >com.fasterxml.jackson.core</ groupId >
       < artifactId >jackson-core</ artifactId >
       < version >${jackson.version}</ version >
     </ dependency >
     < dependency >
       < groupId >com.fasterxml.jackson.core</ groupId >
       < artifactId >jackson-annotations</ artifactId >
       < version >${jackson.version}</ version >
     </ dependency >
     < dependency >
       < groupId >com.fasterxml.jackson.core</ groupId >
       < artifactId >jackson-databind</ artifactId >
       < version >${jackson.version}</ version >
     </ dependency >
     
     < dependency >
         < groupId >jstl</ groupId >
         < artifactId >jstl</ artifactId >
         < version >1.2</ version >
     </ dependency >
     < dependency >
         < groupId >taglibs</ groupId >
         < artifactId >standard</ artifactId >
         < version >1.1.2</ version >
     </ dependency >
     
   </ dependencies >
   < build >
     < finalName >favspringmvcrestful</ finalName >
   </ build >
</ project >


    3.在 web.xml中,配置Spring MVC 4 的DispatcherServlet转发和编码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<? xml  version = "1.0"  encoding = "UTF-8" ?>
< web-app  version = "2.4"  xmlns = "http://java.sun.com/xml/ns/j2ee"
     xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
     < display-name >favblog</ display-name >
 
     < context-param >
         < param-name >contextConfigLocation</ param-name >
         < param-value ></ param-value >
     </ context-param >
 
     < filter >
         < filter-name >encodingFilter</ filter-name >
         < filter-class >org.springframework.web.filter.CharacterEncodingFilter</ filter-class >
         < init-param >
             < param-name >encoding</ param-name >
             < param-value >UTF-8</ param-value >
         </ init-param >
         < init-param >
             < param-name >forceEncoding</ param-name >
             < param-value >true</ param-value >
         </ init-param >
     </ filter >
     < filter-mapping >
         < filter-name >encodingFilter</ filter-name >
         < url-pattern >/*</ url-pattern >
     </ filter-mapping >
 
     < listener >
         < listener-class >org.springframework.web.context.ContextLoaderListener</ listener-class >
     </ listener >
 
     < servlet >
         < servlet-name >springMVC</ servlet-name >
         < servlet-class >org.springframework.web.servlet.DispatcherServlet</ servlet-class >
         < init-param >
             < param-name >contextConfigLocation</ param-name >
             < param-value >classpath*:spring-context.xml</ param-value >
         </ init-param >
         < load-on-startup >1</ load-on-startup >
     </ servlet >
     < servlet-mapping >
         < servlet-name >springMVC</ servlet-name >
         < url-pattern >/</ url-pattern >
     </ servlet-mapping >
</ web-app >
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<? xml  version = "1.0"  encoding = "UTF-8" ?>
< beans  xmlns = "http://www.springframework.org/schema/beans"
     xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
     xmlns:context = "http://www.springframework.org/schema/context"
     xmlns:mvc = "http://www.springframework.org/schema/mvc"
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
         http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
         
     < context:component-scan  base-package = "com.favccxx.favsoft.favjson.controller" ></ context:component-scan >
     
     < mvc:annotation-driven ></ 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/views"  />
         < property  name = "suffix"  value = ".jsp"  />
     </ bean >
</ beans >


    4.新建 FavUser.java 类,测试JSON与Object之间的映射。需要注意的是,如果想对日期进行格式化,在其Getter方法上,使用 @JsonFormat 即可,这样就能输出符合pattern类型的日期,但是这同时也要求输入的日期参数也必须是pattern类型的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package  com.favccxx.favsoft.favjson.pojo;
 
import  java.util.Date;
 
import  com.fasterxml.jackson.annotation.JsonFormat;
 
public  class  FavUser {
     
     private  String userId;
     private  String userName;
     private  int  userAge;
     private  Date createDate;
     
     public  String getUserId() {
         return  userId;
     }
     public  void  setUserId(String userId) {
         this .userId = userId;
     }
     public  String getUserName() {
         return  userName;
     }
     public  void  setUserName(String userName) {
         this .userName = userName;
     }
     public  int  getUserAge() {
         return  userAge;
     }
     public  void  setUserAge( int  userAge) {
         this .userAge = userAge;
     }
     @JsonFormat (pattern= "yyyy-MM-dd HH:mm:ss" )
     public  Date getCreateDate() {
         return  createDate;
     }
     public  void  setCreateDate(Date createDate) {
         this .createDate = createDate;
     }
     
     
 
}

   

    5. 新建FavRestfulController,通过不同的方法测试Spring MVC 4 返回String、Object类型的JSON。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package  com.favccxx.favsoft.favjson.controller;
 
import  java.io.IOException;
 
import  org.springframework.web.bind.annotation.RequestBody;
import  org.springframework.web.bind.annotation.RequestMapping;
import  org.springframework.web.bind.annotation.RequestMethod;
import  org.springframework.web.bind.annotation.RequestParam;
import  org.springframework.web.bind.annotation.RestController;
 
import  com.fasterxml.jackson.core.JsonParseException;
import  com.fasterxml.jackson.databind.JsonMappingException;
import  com.fasterxml.jackson.databind.ObjectMapper;
import  com.favccxx.favsoft.favjson.pojo.FavUser;
 
@RestController
public  class  FavRestfulController {
     
     @RequestMapping (value= "/getUserName" ,method=RequestMethod.POST)
     public  String getUserName( @RequestParam (value= "name" ) String name){
         return  name;
     }
     
     @RequestMapping ( "getFavUser" )
     public  FavUser getFavUser( @RequestParam ( "userName" ) String userName,String userId, int  userAge){
         FavUser favUser =  new  FavUser();
         favUser.setUserId(userId);
         favUser.setUserName(userName);
         favUser.setUserAge(userAge);
         return  favUser;
     }
     
     @RequestMapping ( "getFavUserBody" )
     public  FavUser getFavUserBody( @RequestBody  String body){
         ObjectMapper mapper =  new  ObjectMapper();
         FavUser favUser =  null ;
         try  {
             favUser = mapper.readValue(body,  FavUser. class );
         catch  (JsonParseException e) {
             e.printStackTrace();
         catch  (JsonMappingException e) {
             e.printStackTrace();
         catch  (IOException e) {
             e.printStackTrace();
         }
         return  favUser;
     }
 
}


 6.运行结果如下:

wKioL1RmuWjhdcagAAEnFQ-0h9k100.jpg

wKiom1RmuPeR_IPQAAHCrDPrp7Y273.jpg





本文转自 genuinecx 51CTO博客,原文链接:http://blog.51cto.com/favccxx/1576730,如需转载请自行联系原作者
目录
相关文章
|
15天前
|
缓存 监控 API
构建高效可扩展的RESTful API:后端开发的实践指南
【4月更文挑战第26天】在现代Web开发中,构建一个高效、可扩展且易于维护的RESTful API是后端工程师必须面对的挑战。本文将深入探讨如何利用最佳实践和流行技术,设计出符合REST架构原则的服务端接口。我们将重点讨论API版本控制、资源路由、数据库优化、缓存策略以及安全性考虑等方面,旨在为开发者提供一套综合性解决方案,帮助其提升API的性能与可靠性。
|
3天前
|
设计模式 前端开发 Java
初识Spring MVC
初识Spring MVC
9 0
|
3天前
|
前端开发 Java 应用服务中间件
Spring MVC框架概述
Spring MVC 是一个基于Java的轻量级Web框架,采用MVC设计模型实现请求驱动的松耦合应用开发。框架包括DispatcherServlet、HandlerMapping、Handler、HandlerAdapter、ViewResolver核心组件。DispatcherServlet协调这些组件处理HTTP请求和响应,Controller处理业务逻辑,Model封装数据,View负责渲染。通过注解@Controller、@RequestMapping等简化开发,支持RESTful请求。Spring MVC具有清晰的角色分配、Spring框架集成、多种视图技术支持以及异常处理等优点。
11 1
|
6天前
|
监控 前端开发 Java
SpringBoot与SpringMVC有哪些区别?
SpringBoot和SpringMVC是Java开发中常用的两个框架,它们都是由Spring框架所提供的,但在功能和使用方式上有着一些区别。
18 2
|
11天前
|
缓存 监控 JavaScript
Node.js中构建RESTful API的最佳实践
【4月更文挑战第30天】本文介绍了在Node.js中构建RESTful API的最佳实践:选择合适的框架(如Express、Koa)、设计清晰的API接口(遵循HTTP动词和资源路径)、实现认证授权(JWT、OAuth 2.0)、错误处理、限流缓存、编写文档和测试,以及监控性能优化。这些实践有助于创建健壮、可维护和易用的API。
|
12天前
|
机器学习/深度学习 算法 安全
深度学习在图像识别中的应用与挑战构建高效可扩展的RESTful API:后端开发的实战指南
【4月更文挑战第30天】 随着计算机视觉技术的飞速发展,深度学习在图像识别领域取得了显著的成果。本文将探讨深度学习技术在图像识别中的应用及其所面临的挑战。首先,我们将介绍深度学习的基本原理和关键技术,然后分析其在图像识别中的优势和应用案例。最后,我们将讨论当前深度学习在图像识别领域所面临的主要挑战和未来的发展趋势。
|
12天前
|
缓存 监控 API
|
12天前
|
Java Docker 微服务
|
13天前
|
消息中间件 Java RocketMQ
Spring Cloud RocketMQ:构建可靠消息驱动的微服务架构
【4月更文挑战第28天】消息队列在微服务架构中扮演着至关重要的角色,能够实现服务之间的解耦、异步通信以及数据分发。Spring Cloud RocketMQ作为Apache RocketMQ的Spring Cloud集成,为微服务架构提供了可靠的消息传输机制。
28 1
|
16天前
|
Java 数据安全/隐私保护 Sentinel
微服务学习 | Spring Cloud 中使用 Sentinel 实现服务限流
微服务学习 | Spring Cloud 中使用 Sentinel 实现服务限流