最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用SpringMVC返回json字符串的實例講解

 更新時間:2018年03月27日 09:58:18   作者:過自己想過的生活  
下面小編就為大家分享一篇使用SpringMVC返回json字符串的實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

最近開始接觸SpringMVC這個框架,這個框架使用起來很方便,框架搭起來之后,寫起代碼幾乎都是一個模式。當然要走到這一步必須保證你的SpringMVC的相關(guān)配置都已經(jīng)完成,并且配置正確!

作為我的關(guān)于S平ringMVC的首篇博客,本篇博客主要說名如何配置SpringMVC,并且可以使之正常的返回Bean實體,這里的bean實體一般返回到前端都是以Json字符串的形式返回的。

使用的開發(fā)工具為eclipse,這個也是比較大眾化的開發(fā)工具了,算的上是人人都會使用的了,只是熟練程度不一樣!

具體的配置如下:

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>

還有一個applicationContext.xml,不過我的里面什么都沒有寫,我就不給出了!

新建一個index.jsp,這個作為主界面用來測試各個接口的返回值是否正常!這里也給出代碼:

<%@ 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>

到這里基本上配置方面的都完成了,然后是申明一個Controller,具體的代碼也比較簡單,基本上都是固定的格式!

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;
  }
}

代碼的運行效果如下:

好像不同瀏覽器對于接口的請求操作不一樣,在使用eclipse請求接口,會讓下載一個json文件,文件的內(nèi)容就是一個json字符串。

在配置完整的工程需要用到springframework的jar包,jackson的相關(guān)jar包,我使用的tomcat8.5在運行的時候提示報錯,需要引入common-log的jar包。

在聲明一個返回json字符串的接口時,一定要使用@ResponseBody注解,這個注解會將接口的返回數(shù)據(jù)寫入response中的body區(qū)域,也就是重新傳回前端。

在我測試的時候遇到一個問題,在返回bean的時候,只能返回類包裹,不能返回類繼承或者接口繼承,舉個例子:

如果你返回一個ParentBean,其內(nèi)部包含一個ChildBean,這樣是ok!

如果在接口定義時,返回的是一個父類,而實際返回的是它的子類,這時候匯報錯誤,提示無法將子類轉(zhuǎn)換成父類,就相當于你不能將String對象轉(zhuǎn)換成object對象,關(guān)于這方面應(yīng)該是根據(jù)父類無法查找子類的屬性,導(dǎo)致無法正常將bean對象轉(zhuǎn)換成json字符串,所以在框架中不允許在接口中聲明bean而返回的是bean的子類(這些原因都只是個人猜測,具體的原因還需要分析框架中的代碼)!

好了,關(guān)于返回json字符串就說到這里了!附上demo的源碼,需要的jar包也在里面,需要的可以自己去下載!

源碼下載

以上這篇使用SpringMVC返回json字符串的實例講解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • SpringBoot如何使用mail實現(xiàn)登錄郵箱驗證

    SpringBoot如何使用mail實現(xiàn)登錄郵箱驗證

    在實際的開發(fā)當中,不少的場景中需要我們使用更加安全的認證方式,同時也為了防止一些用戶惡意注冊,我們可能會需要用戶使用一些可以證明個人身份的注冊方式,如短信驗證、郵箱驗證等,這篇文章主要介紹了SpringBoot如何使用mail實現(xiàn)登錄郵箱驗證,需要的朋友可以參考下
    2024-06-06
  • Java源碼跟蹤閱讀技巧【值得收藏】

    Java源碼跟蹤閱讀技巧【值得收藏】

    今天跟大家分享一下我平時閱讀源碼的幾個小技巧,對于閱讀Java中間件如Spring、Dubbo等框架源碼的同學(xué)有一定幫助。本文基于Eclipse IDE,感興趣的朋友跟隨小編一起看看吧
    2018-11-11
  • JAVA Integer類型自加實例詳解

    JAVA Integer類型自加實例詳解

    這篇文章主要介紹了JAVA Integer類型自加實例詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-05-05
  • 關(guān)于文件合并與修改md5值的問題

    關(guān)于文件合并與修改md5值的問題

    這篇文章主要介紹了關(guān)于文件合并與修改md5值的問題,使用本博客的方法,不僅僅可以修改md5值,還可以達到隱藏文件的目的,需要的朋友可以參考下
    2023-04-04
  • Java文件批量重命名批量提取特定類型文件

    Java文件批量重命名批量提取特定類型文件

    這篇文章主要介紹了Java文件批量重命名批量提取特定類型文件的相關(guān)資料
    2016-08-08
  • Java畫筆的簡單實用方法

    Java畫筆的簡單實用方法

    這篇文章主要介紹了Java畫筆的簡單實用方法,需要的朋友可以參考下
    2017-09-09
  • JDK8并行流及串行流區(qū)別原理詳解

    JDK8并行流及串行流區(qū)別原理詳解

    這篇文章主要介紹了JDK8并行流及串行流區(qū)別原理詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-07-07
  • IDEA檢查項目的jdk版本需要看的地方

    IDEA檢查項目的jdk版本需要看的地方

    這篇文章主要介紹了IDEA檢查項目的jdk版本需要看的地方,文中通過圖文介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-06-06
  • Java中的定時器Timer詳解

    Java中的定時器Timer詳解

    這篇文章主要為大家詳細介紹了Java定時器Timer的使用方法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-08-08
  • 完美解決Logback configuration error detected的問題

    完美解決Logback configuration error detected的問題

    這篇文章主要介紹了完美解決Logback configuration error detected的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08

最新評論

陵水| 老河口市| 随州市| 扬州市| 巴塘县| 台州市| 罗山县| 晋江市| 灵武市| 寻乌县| 通海县| 稻城县| 库伦旗| 临湘市| 屯留县| 南澳县| 隆昌县| 巴彦县| 云林县| 都安| 沙湾县| 南皮县| 阿荣旗| 乐清市| 大邑县| 天门市| 万源市| 凤凰县| 鲜城| 江津市| 鸡泽县| 西安市| 东港市| 鄂伦春自治旗| 惠来县| 随州市| 蕲春县| 剑川县| 文水县| 封丘县| 江口县|