spring mvc 返回json数据的四种方式


一.返回ModelAndView,其中包含map集

复制代码
/* * 返回ModelAndView类型的结果 * 检查用户名的合法性,如果用户已经存在,返回false,否则返回true(返回json数据,格式为{"valid",true}) */ @RequestMapping(value = "/checkNameExistsMethod2", produces = "application/json;charset=UTF-8") //这里的produces值在不设置的情况下将根据返回结果自动决定 public @ResponseBody ModelAndView checkNameValidMethod2(@RequestParam String name) { boolean result = true; //... Map<String, Boolean> map = new HashMap<>(); map.put("valid", result); return new ModelAndView(new MappingJackson2JsonView(), map); }
复制代码

 

 
二.返回String类型的json,这里有两种方式。

方式一:使用jackson-databind-x.x.x.jar包中的ObjectMapper将Map型数据改写为String并返回

复制代码
  /* * 返回String类型的结果 * 检查用户名的合法性,如果用户已经存在,返回false,否则返回true(返回json数据,格式为{"valid",true}) */ @RequestMapping(value = "/checkNameExistsMethod1", produces = "application/json;charset=UTF-8") public @ResponseBody String checkNameValidMethod1(@RequestParam String name) { boolean result = true; //... Map<String, Boolean> map = new HashMap<>(); map.put("valid", result); ObjectMapper mapper = new ObjectMapper(); String resultString = ""; try { resultString = mapper.writeValueAsString(map); } catch (JsonProcessingException e) { e.printStackTrace(); } return resultString; }
复制代码

 

 

方式二:

直接返回字符串,主要key/value值必须使用含有转义字符\的双引号,单引号无效 

复制代码
 /* * 返回String类型的结果 * 检查用户名的合法性,如果用户已经存在,返回false,否则返回true(返回json数据,格式为{"valid",true}) */ @RequestMapping(value = "/checkNameExistsMethod1", produces = "application/json;charset=UTF-8") public @ResponseBody String checkNameValidMethod1(@RequestParam String name) { boolean result = true; String resultString = "{\"result\":true}"; //注意一定是双引号 "{\"result\":\"success\"}" return resultString; }
复制代码

 

三.返回任何预定义class类型的结果:

复制代码
@RequestMapping(value = "/findEmployeebyName")
    public @ResponseBody Employee findEmployeebyName(String name) { List<Employee> lstEmployees = employeeService.getAllEmployees(); for (Employee employee : lstEmployees) { if (employee.getName().equals(name)) return employee; } return null; }
复制代码

这里的Employ必须事先定义好。

四.使用HttpServletResponse对象的response.getWriter().write(xxx)方法

 

 

复制代码
@RequestMapping(value="/forbiddenUser")
    public void forbiddenUser(int id,HttpServletRequest request,HttpServletResponse response) { String resultString="{\"result\":\"success\"}";//注意一定是双引号 "{\"result\":true}" try { response.setContentType("application/json"); response.getWriter().write(resultString); } catch (IOException e) { e.printStackTrace(); } }

spring4mvc返回json(bean,list,map)

  因为spring3和spring4的mvc在前端返回json所需要的jar包不一样,所以索性写一篇关于spring4mvc在前端返回json的博文。

首先,新建一个web项目,项目格式如图所示:

 

convertJsonAction:springmvc的action类

inde.jsp:有三个按钮,分别返回bean,list和map对应的json

然后是引入的library:分别是spring-core,spring-mvc,spring-web,servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <!-- 将配置对应的springmvc文件设置在src根目录下 --> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping>

复制代码

 

然后在src下面新建一个叫springmvc的xml文件,文件内容如图所示:

复制代码
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> </beans>
复制代码

 

接着我们在ConvertJSonAction.java类中添加一个方法:

复制代码
package com.mz.json; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * controller指明这是一个springmvc的action类 * requestMapping是总的路径,所有访问这个action类中的方法必须通过/convert * @author asus * */ @Controller @RequestMapping("/convert") public class ConvertJsonAction { //responseBody是指返回的User是一个json对象(也可以是string或者xml对象) @RequestMapping("/bean2json") public @ResponseBody User bean2json() { User user = new User(); user.setId(1); user.setUsername("Irasel"); return user; } }
复制代码

 

 这是action的处理类,接着我们在springmvc中配置开启mvc的annotation和扫描标签:

<mvc:annotation-driven /> <context:component-scan base-package="com.mz.json"></context:component-scan>

 

index.jsp中添加三个按钮,每一个按钮分别对应的返回一个bean对象的json,list对象的json和map对象的json:

复制代码
 <!-- 点击返回一个bean对象的json --> <input type="button" value="bean2json"><br/> <!-- 点击返回一个list对象的json --> <input type="button" value="list2json"> <br/> <!-- 点击返回一个map对象的json --> <input type="button" value="map2json"><br/>
复制代码

 

使用jquery的异步传输:

复制代码
    $(':button:first').click(function(){ var url = 'convert/bean2json.action'; var arg =null; $.post(url,arg,function(returnData){ console.log(returnData); }); });
复制代码

 

效果如图所示:

接着是list和map的方法(不再粘贴效果图了,反正都差不多)

复制代码
    @RequestMapping("/list2json")
    public @ResponseBody List<User> list2Json() { List<User> users = new ArrayList<User>(); User user1 = new User(); user1.setId(1); user1.setUsername("Irasel"); User user2 = new User(); user2.setId(2); user2.setUsername("路西法"); User user3 = new User(); user3.setId(3); user3.setUsername("Micheal"); users.add(user1); users.add(user2); users.add(user3); return users; } @RequestMapping("/map2json") public @ResponseBody Map<String, Object> map2Json() { List<User> users = new ArrayList<User>(); Map<String, Object> map = new HashMap<String, Object>(); User user1 = new User(); user1.setId(1); user1.setUsername("Irasel"); User user2 = new User(); user2.setId(2); user2.setUsername("路西法"); User user3 = new User(); user3.setId(3); user3.setUsername("Micheal"); users.add(user1); users.add(user2); users.add(user3); map.put("row", users.size()); map.put("users", users); return map; }

 

SpringMVC通过实体类返回json格式的字符串,并在前端显示

一.除了搭建springmvc框架需要的jar包外,还需要这两个jar包

jackson-core-asl-1.9.2.jar和jackson-mapper-asl-1.9.2.jar

二.web,.xml配置

1
classpath:spring-servlet.xml指定springmvc配置文件的位置
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
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 
   
   <servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-servlet.xml</param-value>
    </init-param>
    <!-- 可以自定义servlet.xml配置文件的位置和名称,默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如spring-servlet.xml
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-servlet.xml</param-value>  默认
    </init-param>
    -->
    <load-on-startup>1</load-on-startup>
</servlet>
  
<servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>
 
</web-app>

三.spring-servlet.xml配置

通过此配置,将实体类自动返回为json格式的数据

复制代码
<?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:p="http://www.springframework.org/schema/p" 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-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!-- 启用spring mvc 注解 --> <context:annotation-config /> <!-- 设置使用注解的类所在的jar包 --> <context:component-scan base-package="me.mvc,me.base"></context:component-scan> <!-- 完成请求和注解POJO的映射 --> <!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> --> <!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/jsp/" p:suffix=".jsp" />
   <!-- 通过实体类返回json格式数据的关键配置 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <!--返回字符串格式json--> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="102400000"></property> </bean> </beans>
复制代码

四,后台java代码

复制代码
package me.mvc; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import me.mvc.service.testmvcDao; import net.sf.json.JSONArray; import org.apache.struts2.ServletActionContext; import org.springframework.http.HttpRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/mvc/*") public class testmvc { @RequestMapping(method=RequestMethod.GET,value="/hello22index.do")//第一步访问hello2页面 public String index2() { return "hello2"; } @ResponseBody @RequestMapping(method=RequestMethod.POST,value="/hello22.do")//第二步前台发送ajax请求调用此方法并返回json数据 public User index2post(String testname1 ,HttpServletResponse response) throws IOException { System.out.println("*************:"+testname1); User u=new User(); u.setUsername("name"); u.setUserpassword("pass"); return u; } }
复制代码

五.前端页面

该方法sendajax()将向后台发送请求,调用index2post()方法,返回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
50
51
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
   <script type="text/javascript" src="../../js/jquery-1.12.0.js"></script>
    <base href="<%=basePath%>">
     
    <title>My JSP 'hello2.jsp' starting page</title>
     
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">   
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
 
 <script type="text/javascript" src="<%=path%>/js/jquery-1.12.0.js"></script></head>
   
  <body>
 
      <input type="text" name="testname" id="testname1">
 
       <input type="button" value="ajax提交" onclick="sendajax()">
  
</form>
  </body>
  <script type="text/javascript">
   function  sendajax()
   {  
       var testname1=$("#testname1").val();
       alert(testname1);
       $.ajax({
            type: "post",
            url: "<%=path%>/mvc/hello22.do", 
            data: {testname1:testname1},            
            dataType: "json",           
            success: function (data) { 
             alert(data.username);
                  
             },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
             alert("系统繁忙,请稍后重试!");               
      }
    });
   }
  </script>
</html>

  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM