一.返回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); }
方式一:使用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 >
|