springMVC中 controller的返回值测试
springMVC的返回值有ModelAndView,String,void,Object类型。今天就来整理一下。
目录结构:
依赖:
<!-- jackson --> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.10.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.10.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.10.0</version> </dependency>
老版本的Jackson使用的包名为org.codehaus.jackson,而新版本使用的是com.fasterxml.jackson。
Jackson主要包含了3个模块:
- jackson-core
- jackson-annotations
- jackson-databind
其中,jackson-annotations依赖于jackson-core,jackson-databind又依赖于jackson-annotations。
Jackson有三种方式处理Json:
- 使用底层的基于Stream的方式对Json的每一个小的组成部分进行控制
- 使用Tree Model,通过JsonNode处理单个Json节点
- 使用databind模块,直接对Java
对象进行序列化和反序列化
关键代码:
ReturnValueController
package com.kaspar.controller; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping(value="/returnValue") public class ReturnValueController { @RequestMapping("/returnModelAndView") //返回ModelAndView public ModelAndView doModelAndView(String name, String password, ModelAndView mav){ mav.addObject("name", name); mav.addObject("password", password); mav.setViewName("/showReturn.jsp"); return mav; } @RequestMapping("/returnString") //返回String类型, 可以通过HttpServletRequest 来传递参数 public String doString(String sname, String spassword, HttpServletRequest request){ request.setAttribute("sname", sname); request.setAttribute("spassword", spassword); return "/showReturn.jsp"; } @RequestMapping("/returnVoid") //无返回值,通过ServletAPI完成参数传递和跳转 public void doVoid(String vname, String vpassword, HttpServletRequest request, HttpServletResponse response) throws Exception{ request.setAttribute("vname", vname); request.setAttribute("vpassword", vpassword); request.getRequestDispatcher("/showReturn.jsp").forward(request, response); } @RequestMapping("/returnObjectValue") //返回Object对象需要开启消息转换器HttpMessageConverter,<mvc:annotation-driven/> @ResponseBody public Object doObjectValue(){ return 12.34; } @RequestMapping("/returnObjectString") //返回String @ResponseBody public Object doObjectString(){ return "Hello SpringMVC"; } @RequestMapping("/returnObjectList") //返回List @ResponseBody public Object doObjectList(){ List<String> list = new ArrayList<String>(); list.add("String1"); list.add("String2"); list.add("String3"); return list; } @RequestMapping("/returnObjectMap") //返回Map @ResponseBody public Object doObjectMap(){ Map<String, String> map = new HashMap<String, String>(); map.put("mk1", "kv1"); map.put("mk2", "kv2"); map.put("mk3", "kv3"); return map; } }
Spring-mvc.xml
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.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"> <!-- 开启驱动器注解 --> <mvc:annotation-driven /> <!-- 静态资源设置,因为需要加入js静态资源 --> <mvc:resources location="/js/" mapping="/js/**"/> <!-- 扫描注解 --> <context:component-scan base-package="com.kaspar.controller" /> </beans>
测试页面returnValue.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"%> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!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=UTF-8"> <base href="<%=basePath%>"> <title>ReturnValue</title> <script type="text/javascript" src="js/jquery-1.9.0.min.js"></script> <script type="text/javascript"> $(function() { //获取value值得ajax $("#value").on("click", function() { alert("123"); $.ajax({ type : "get", url : "returnValue/returnObjectValue.do", success : function(data) { alert("data: " + data); } }); }); //获取String值得ajax $("#string").on("click", function() { alert("123"); $.ajax({ type : "get", url : "returnValue/returnObjectString.do", success : function(data) { alert("data: " + data); } }); }); //获取List值得ajax $("#list").on("click", function() { alert("123"); $.ajax({ type : "get", url : "returnValue/returnObjectList.do", success : function(data) { for (var i = 0; i < data.length; i++) alert("data: " + data[i]); } }); }); //获取Map值得ajax $("#map").on("click", function() { alert("123"); $.ajax({ type : "get", url : "returnValue/returnObjectMap.do", success : function(data) { for ( var key in data) { alert("key: " + key + " value: " + data[key]); } } }); }); }); </script> </head> <body> 返回ModelAndView <form action="returnValue/returnModelAndView.do"> name: <input type="text" name="name"><br /> password:<input type="text" name="name"><br /> <input type="submit" value="submit"> </form> <hr> 返回String类型 <form action="returnValue/returnString.do"> name: <input type="text" name="sname"><br /> password:<input type="text" name="spassword"><br /> <input type="submit" value="submit"> </form> <hr> 无返回值 <form action="returnValue/returnVoid.do"> name: <input type="text" name="vname"><br /> password:<input type="text" name="vname"><br /> <input type="submit" value="submit"> </form> <hr> 返回Object对象,类型为数值型 <input id="value" type="button" value="AjaxgetValue"> <hr> 返回Object对象,类型为String <input id="string" type="button" value="AjaxgetString"> <hr> 返回Object对象,类型为List <input id="list" type="button" value="AjaxgetList"> <hr> 返回Object对象,类型为Map <input id="map" type="button" value="AjaxgetMap"> </body> </html>
跳转后的页面showReturn.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!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=UTF-8"> <base href="<%=basePath %>"> <title>ShowReturn</title> </head> <body> 返回ModelAndView <div> <h3><c:out value="${name }" /></h3> <h3><c:out value="${password }" /></h3> </div> <hr> 返回String类型 <div> <h3><c:out value="${sname }" /></h3> <h3><c:out value="${spassword }" /></h3> </div> <hr> 无返回值 <div> <h3><c:out value="${vname }" /></h3> <h3><c:out value="${vpassword }" /></h3> </div> </body> </html>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:config/Spring-mvc.xml</param-value> </init-param> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- 解决中文乱码 --> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
作者:Kaspar_Choo
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。