使用Spring RESTful服务接收和返回JSON最佳实践

首先要导入相应的架包

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.8.7</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-core</artifactId>
   <version>2.8.7</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-annotations</artifactId>
   <version>2.8.7</version>
</dependency>

然后再

<!-- 添加的两个 自动配置器(restful 风格所必须) -->
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>

以下为前端的相关ajax请求

function sendNews()
{
var url="${pageContext.request.contextPath}/NewsAction/addNews";
var title = "title="+$('#title').val();
var author = "author="+$('#author').val();
var content = "content="+UE.getEditor('container').getContent();

var dataText = title+"&"+author+"&"+content;
alert("dataText:   "+dataText);
$.ajax({
url:url,

dataType:"text",  /* 后端  返回值类型 为  String 时  此处 必须指定  dataType 为 text */ 
data:dataText,

type:"post",
success:function(rspText)
{
alert("哈哈哈哈");
alert("rspText:  "+rspText);
}
});
}

以下为具体的实现类


@RequestMapping(value="addNews",produces="application/json;charset=utf-8")
@ResponseBody
public News   addNews(News news)
{  
System.out.println("--------- 添加  news ---------");
news.setId(UUID.randomUUID().toString());
news.setNewsdate(new Date().toString());
String newsStr = "";
try
{
newsStr = new ObjectMapper().writeValueAsString(news);
System.out.println("newsStr:\t"+newsStr);
}
catch (JsonProcessingException e) {
e.printStackTrace();
}
String a = "{'id':'fae9acde-2808-4153-ae50-c15f7b7b94b6','title':null,'content':null,'newsdate':'Tue Apr 11 12:20:39 CST 2017','author':null}";;

return news;

}

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

一、实验环境的搭建

1、Spring mvc jar。

导入spring mvc运行所需jar包。导入如下(有多余)

 

 

2、json的支持jar

 

 

 

3、加入jQuery。

选用jquery-3.0.0.min.js,放在WebRoot/JS文件夹

 

 

导入jQuery到jsp页面如下

 

 

 

4、web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

  <display-name>springmvcjson</display-name>

  <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:springmvc.xml</param-value>

  </init-param>

  <load-on-startup>1</load-on-startup>

  </servlet>

 

  <servlet-mapping>

  <servlet-name>springmvc</servlet-name>

  <url-pattern>*.action</url-pattern>

  </servlet-mapping>

 

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

</web-app>

 

5、springmvc.xml

classpath下

<beans xmlns="http://www.springframework.org/schema/beans"

         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"

         xmlns:context="http://www.springframework.org/schema/context"

         xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"

         xsi:schemaLocation="http://www.springframework.org/schema/beans

                   http://www.springframework.org/schema/beans/spring-beans-3.2.xsd

                   http://www.springframework.org/schema/mvc

                   http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd

                   http://www.springframework.org/schema/context

                   http://www.springframework.org/schema/context/spring-context-3.2.xsd

                   http://www.springframework.org/schema/aop

                   http://www.springframework.org/schema/aop/spring-aop-3.2.xsd

                   http://www.springframework.org/schema/tx

                   http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

        

         <!-- <bean name="/test01.action" class="com.xzw.json.controller.JsonTest"></bean> -->

         <!-- View -->

         <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"></bean>

        

        

         <!-- 注解映射和适配器 -->

         <mvc:annotation-driven ></mvc:annotation-driven>

        

  

  

         <!-- 组件扫描 -->

         <context:component-scan base-package="com.xzw.json.controller"></context:component-scan>

        

         <!-- 使用@Autowired、@Required等注解

         如不必设置<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor "/>和

         <bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>等等

         -->

         <context:annotation-config /> 

        

 

</beans>

 

二、实验例子编写

 

1、请求和返回都是JSON

a).程序发起

index.jsp的一个按钮

 

 

 

b).js函数

 

 

function requestByJson() {

         $.ajax({

                   type : 'post',

                   url : '${pageContext.request.contextPath}/jsonsource.action',

                   //设置contentType类型为json

                   contentType : 'application/json;charset=utf-8',

                   //json数据

                   data : '{"username":"reader001","password":"psw001"}',

                   //请求成功后的回调函数

                   success : function(data) {

                            alert(data.username);

                   }

         });

}

 

c).Controller/Mapping

@RequestMapping("/jsonsource")

//@RequestBody 将json对象转成java对象

//@ResponseBody 表示返回的是json对象

public @ResponseBody User jsonSource(@RequestBody User user){

        

         return user;

}

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值