使用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,如需转载请自行联系原作者
目录
相关文章
|
4月前
|
人工智能 Java Nacos
基于 Spring AI Alibaba + Nacos 的分布式 Multi-Agent 构建指南
本文将针对 Spring AI Alibaba + Nacos 的分布式多智能体构建方案展开介绍,同时结合 Demo 说明快速开发方法与实际效果。
3720 80
|
6月前
|
JSON 人工智能 Java
基于Spring AI构建智能Text-to-SQL转换器:一个完整的MCP
Spring AI 更新结构化输出转换器,弃用旧版 Parser 类,引入与 Spring 框架对齐的 Converter 体系,提升命名规范与功能兼容性。新版本支持 JSON、XML 及 Java 对象转换,确保 LLM 输出结构化,便于下游应用处理。
|
6月前
|
监控 Java API
Spring Boot 3.2 结合 Spring Cloud 微服务架构实操指南 现代分布式应用系统构建实战教程
Spring Boot 3.2 + Spring Cloud 2023.0 微服务架构实践摘要 本文基于Spring Boot 3.2.5和Spring Cloud 2023.0.1最新稳定版本,演示现代微服务架构的构建过程。主要内容包括: 技术栈选择:采用Spring Cloud Netflix Eureka 4.1.0作为服务注册中心,Resilience4j 2.1.0替代Hystrix实现熔断机制,配合OpenFeign和Gateway等组件。 核心实操步骤: 搭建Eureka注册中心服务 构建商品
1089 3
|
5月前
|
人工智能 Java API
构建基于Java的AI智能体:使用LangChain4j与Spring AI实现RAG应用
当大模型需要处理私有、实时的数据时,检索增强生成(RAG)技术成为了核心解决方案。本文深入探讨如何在Java生态中构建具备RAG能力的AI智能体。我们将介绍新兴的Spring AI项目与成熟的LangChain4j框架,详细演示如何从零开始构建一个能够查询私有知识库的智能问答系统。内容涵盖文档加载与分块、向量数据库集成、语义检索以及与大模型的最终合成,并提供完整的代码实现,为Java开发者开启构建复杂AI智能体的大门。
2808 58
|
4月前
|
缓存 监控 Java
《深入理解Spring》性能监控与优化——构建高性能应用的艺术
本文系统介绍了Spring生态下的性能监控与优化实践,涵盖监控体系构建、数据库调优、缓存策略、线程池配置及性能测试等内容,强调通过数据驱动、分层优化和持续迭代提升应用性能。
|
4月前
|
前端开发 Java 微服务
《深入理解Spring》:Spring、Spring MVC与Spring Boot的深度解析
Spring Framework是Java生态的基石,提供IoC、AOP等核心功能;Spring MVC基于其构建,实现Web层MVC架构;Spring Boot则通过自动配置和内嵌服务器,极大简化了开发与部署。三者层层演进,Spring Boot并非替代,而是对前者的高效封装与增强,适用于微服务与快速开发,而深入理解Spring Framework有助于更好驾驭整体技术栈。
|
4月前
|
负载均衡 Java API
《深入理解Spring》Spring Cloud 构建分布式系统的微服务全家桶
Spring Cloud为微服务架构提供一站式解决方案,涵盖服务注册、配置管理、负载均衡、熔断限流等核心功能,助力开发者构建高可用、易扩展的分布式系统,并持续向云原生演进。
|
5月前
|
XML Java 测试技术
使用 Spring 的 @Import 和 @ImportResource 注解构建模块化应用程序
本文介绍了Spring框架中的两个重要注解`@Import`和`@ImportResource`,它们在模块化开发中起着关键作用。文章详细分析了这两个注解的功能、使用场景及最佳实践,帮助开发者构建更清晰、可维护和可扩展的Java应用程序。
311 0
|
7月前
|
前端开发 Java API
Spring Cloud Gateway Server Web MVC报错“Unsupported transfer encoding: chunked”解决
本文解析了Spring Cloud Gateway中出现“Unsupported transfer encoding: chunked”错误的原因,指出该问题源于Feign依赖的HTTP客户端与服务端的`chunked`传输编码不兼容,并提供了具体的解决方案。通过规范Feign客户端接口的返回类型,可有效避免该异常,提升系统兼容性与稳定性。
531 0