使用SpringMVC返回json字符串的實(shí)例講解
最近開(kāi)始接觸SpringMVC這個(gè)框架,這個(gè)框架使用起來(lái)很方便,框架搭起來(lái)之后,寫(xiě)起代碼幾乎都是一個(gè)模式。當(dāng)然要走到這一步必須保證你的SpringMVC的相關(guān)配置都已經(jīng)完成,并且配置正確!
作為我的關(guān)于S平ringMVC的首篇博客,本篇博客主要說(shuō)名如何配置SpringMVC,并且可以使之正常的返回Bean實(shí)體,這里的bean實(shí)體一般返回到前端都是以Json字符串的形式返回的。
使用的開(kāi)發(fā)工具為eclipse,這個(gè)也是比較大眾化的開(kāi)發(fā)工具了,算的上是人人都會(huì)使用的了,只是熟練程度不一樣!
具體的配置如下:
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"
id="WebApp_ID" version="3.1">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<display-name>ReturnJsonDemo</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:dispatcher-servlet.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
dispatcher-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<mvc:default-servlet-handler />
<context:component-scan base-package="com.zyq.springmvc.controller">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Service" />
</context:component-scan>
<context:annotation-config />
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json; charset=UTF-8</value>
<value>application/x-www-form-urlencoded; charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
</beans>
還有一個(gè)applicationContext.xml,不過(guò)我的里面什么都沒(méi)有寫(xiě),我就不給出了!
新建一個(gè)index.jsp,這個(gè)作為主界面用來(lái)測(cè)試各個(gè)接口的返回值是否正常!這里也給出代碼:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Main Page</title>
</head>
<body>
<h1>Welcome Main Page!!!</h1>
<form action="/ReturnJsonDemo/first">
<input type="submit" value="first" />
</form>
<form action="/ReturnJsonDemo/second">
<input type="submit" value="second" />
</form>
<form action="/ReturnJsonDemo/third">
<input type="submit" value="third" />
</form>
<form action="/ReturnJsonDemo/fourth">
<input type="submit" value="fourth" />
</form>
</body>
</html>
到這里基本上配置方面的都完成了,然后是申明一個(gè)Controller,具體的代碼也比較簡(jiǎn)單,基本上都是固定的格式!
MainController.java
package com.zyq.springmvc.controller;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zyq.springmvc.bean.CommonBean;
import com.zyq.springmvc.bean.SonBean;
@Controller
public class MainController {
@RequestMapping("/first")
@ResponseBody
public CommonBean getFirst(){
CommonBean bean = new CommonBean();
bean.setResultCode("success");
bean.setTimeStamp(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(System.currentTimeMillis()));
bean.setData("this is first message");
return bean;
}
@RequestMapping("/second")
@ResponseBody
public CommonBean getSecond(){
CommonBean bean = new CommonBean();
bean.setResultCode("success");
bean.setTimeStamp(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(System.currentTimeMillis()));
List<String> data = new ArrayList<>();
data.add("JAVA");
data.add("C");
data.add("PYTHON");
data.add("C++");
bean.setData(data);
return bean;
}
@RequestMapping("/third")
@ResponseBody
public CommonBean getThird(){
CommonBean bean = new CommonBean();
bean.setResultCode("success");
bean.setTimeStamp(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(System.currentTimeMillis()));
Map<String, String> data = new HashMap<>();
data.put("first", "JAVA");
data.put("second","PYTHON");
data.put("third", "C++");
data.put("fourth", "C");
bean.setData(data);
return bean;
}
@RequestMapping("/fourth")
@ResponseBody
public CommonBean getFourth(){
CommonBean bean = new CommonBean();
bean.setResultCode("success");
bean.setTimeStamp(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(System.currentTimeMillis()));
SonBean sonBean = new SonBean();
sonBean.setAge(25);
sonBean.setName("Hacker's Delight");
sonBean.setGender("male");
bean.setData(sonBean);
return bean;
}
}
代碼的運(yùn)行效果如下:

好像不同瀏覽器對(duì)于接口的請(qǐng)求操作不一樣,在使用eclipse請(qǐng)求接口,會(huì)讓下載一個(gè)json文件,文件的內(nèi)容就是一個(gè)json字符串。
在配置完整的工程需要用到springframework的jar包,jackson的相關(guān)jar包,我使用的tomcat8.5在運(yùn)行的時(shí)候提示報(bào)錯(cuò),需要引入common-log的jar包。
在聲明一個(gè)返回json字符串的接口時(shí),一定要使用@ResponseBody注解,這個(gè)注解會(huì)將接口的返回?cái)?shù)據(jù)寫(xiě)入response中的body區(qū)域,也就是重新傳回前端。
在我測(cè)試的時(shí)候遇到一個(gè)問(wèn)題,在返回bean的時(shí)候,只能返回類(lèi)包裹,不能返回類(lèi)繼承或者接口繼承,舉個(gè)例子:
如果你返回一個(gè)ParentBean,其內(nèi)部包含一個(gè)ChildBean,這樣是ok!
如果在接口定義時(shí),返回的是一個(gè)父類(lèi),而實(shí)際返回的是它的子類(lèi),這時(shí)候匯報(bào)錯(cuò)誤,提示無(wú)法將子類(lèi)轉(zhuǎn)換成父類(lèi),就相當(dāng)于你不能將String對(duì)象轉(zhuǎn)換成object對(duì)象,關(guān)于這方面應(yīng)該是根據(jù)父類(lèi)無(wú)法查找子類(lèi)的屬性,導(dǎo)致無(wú)法正常將bean對(duì)象轉(zhuǎn)換成json字符串,所以在框架中不允許在接口中聲明bean而返回的是bean的子類(lèi)(這些原因都只是個(gè)人猜測(cè),具體的原因還需要分析框架中的代碼)!
好了,關(guān)于返回json字符串就說(shuō)到這里了!附上demo的源碼,需要的jar包也在里面,需要的可以自己去下載!
以上這篇使用SpringMVC返回json字符串的實(shí)例講解就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java 中函數(shù) Function 的使用和定義示例小結(jié)
這篇文章主要介紹了Java 中函數(shù) Function 的使用和定義小結(jié),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-07-07
java執(zhí)行SQL語(yǔ)句實(shí)現(xiàn)查詢(xún)的通用方法詳解
這篇文章主要介紹了java執(zhí)行SQL語(yǔ)句實(shí)現(xiàn)查詢(xún)的通用方法詳解,具有一定借鑒價(jià)值,需要的朋友可以參考下。2017-12-12
Java替換視頻背景音樂(lè)的實(shí)現(xiàn)示例
FFmpeg 是一個(gè)強(qiáng)大的開(kāi)源多媒體處理工具,被廣泛應(yīng)用于音視頻的錄制、轉(zhuǎn)碼、編輯等方面,本文主要介紹了Java替換視頻背景音樂(lè),具有一定的參考價(jià)值,感興趣的可以了解一下2024-03-03
淺談SpringBoot項(xiàng)目如何讓前端開(kāi)發(fā)提高效率(小技巧)
這篇文章主要介紹了淺談SpringBoot項(xiàng)目如何讓前端開(kāi)發(fā)提高效率(小技巧),主要介紹了Swagger和Nginx提高效率的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-04-04
Java編程實(shí)現(xiàn)NBA賽事接口調(diào)用實(shí)例代碼
這篇文章主要介紹了Java編程實(shí)現(xiàn)NBA賽事接口調(diào)用實(shí)例代碼,具有一定參考價(jià)值,需要的朋友可以了解下。2017-11-11
Java?C++刷題leetcode1106解析布爾表達(dá)式
這篇文章主要為大家介紹了Java?C++刷題leetcode1106解析布爾表達(dá)式示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01

