当前位置: 移动技术网 > IT编程>开发语言>Java > 使用SpringMVC返回json字符串的实例讲解

使用SpringMVC返回json字符串的实例讲解

2019年07月19日  | 移动技术网IT编程  | 我要评论

东方不败之唯一东方,夕字五笔怎么打,伟星新材

最近开始接触springmvc这个框架,这个框架使用起来很方便,框架搭起来之后,写起代码几乎都是一个模式。当然要走到这一步必须保证你的springmvc的相关配置都已经完成,并且配置正确!

作为我的关于s平ringmvc的首篇博客,本篇博客主要说名如何配置springmvc,并且可以使之正常的返回bean实体,这里的bean实体一般返回到前端都是以json字符串的形式返回的。

使用的开发工具为eclipse,这个也是比较大众化的开发工具了,算的上是人人都会使用的了,只是熟练程度不一样!

具体的配置如下:

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文件,文件的内容就是一个json字符串。

在配置完整的工程需要用到springframework的jar包,jackson的相关jar包,我使用的tomcat8.5在运行的时候提示报错,需要引入common-log的jar包。

在声明一个返回json字符串的接口时,一定要使用@responsebody注解,这个注解会将接口的返回数据写入response中的body区域,也就是重新传回前端。

在我测试的时候遇到一个问题,在返回bean的时候,只能返回类包裹,不能返回类继承或者接口继承,举个例子:

如果你返回一个parentbean,其内部包含一个childbean,这样是ok!

如果在接口定义时,返回的是一个父类,而实际返回的是它的子类,这时候汇报错误,提示无法将子类转换成父类,就相当于你不能将string对象转换成object对象,关于这方面应该是根据父类无法查找子类的属性,导致无法正常将bean对象转换成json字符串,所以在框架中不允许在接口中声明bean而返回的是bean的子类(这些原因都只是个人猜测,具体的原因还需要分析框架中的代码)!

好了,关于返回json字符串就说到这里了!附上demo的源码,需要的jar包也在里面,需要的可以自己去下载!

以上这篇使用springmvc返回json字符串的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网