此篇文章的讲解是基于前几篇文章的内容,如果大家有看不懂的地方可以看前几篇的内容.
spring mvc返回json数据可方法常用的有
- 直接PrintWriter 输出
- 使用Spring内置的支持
下面我分别对上面的两种方法进行讲解:注意这篇文章的讲解使用的是spring3.2版本,此版本与spring 3.0的配置有少许不同,希望大家注意,同时我使用的是jquery做演示.
首先讲解直接PrintWriter 输出,这个是最简单的,但是不可以使用java的复杂对象.
没有什么需要配置的,直接请求我们的ajax请求页面json.jsp.
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <base href="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/">
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <script type="text/javascript" src="script/jquery-1.8.3.js"></script>
- <title>添加用户</title>
- <script type="text/javascript">
- $(function(){
- $("form :button").click(function(){
- var name = $("#name").val();
- var age = $("#age").val();
- $.ajax({
- type: "POST",
- url: "user/addUser",
- data: {name:name , age:age},
- success:function(data){
- alert("名字:" + data.name + "年龄:" + data.age);
- }
- });
- });
- });
- </script>
- </head>
- <body>
- <form action="user/addUser" method="post">
- 用户名:<input type="text" id="name" name="name" /><br/>
- 年龄:<input type="text" id="age" name="age" />
- <input type="button" value="提交" />
- </form>
- </body>
- </html>
给提示按钮添加点击事件,当提交表单时获取用户名name,和年龄age,以post的方式提交表user/addUser,并把服务器返回的数据显示出来,这里要注意JSP页面头上最好加上
- <base href="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/">
使用绝对路径,一切从根目录开始找起,要不然会因为路径问题,而且很烦,js也要声明为spring mvc不要拦截,这里之前文章有说过
Controller:
- package gd.hz.springmvc.controller;
-
- import java.io.IOException;
- import java.io.PrintWriter;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- import gd.hz.springmvc.model.User;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
-
- @Controller("userController")
- @RequestMapping("user")
- public class UserController {
-
-
- @RequestMapping("addUser")
- public void addUser(User user, HttpServletRequest request,
- HttpServletResponse response) {
-
- System.out.println("过来了");
- String result = "{\"name\":\"" + user.getName() + "\"}";
- PrintWriter out = null;
- System.out.println(result);
- response.setContentType("application/json");
- try {
- out = response.getWriter();
- out.write(result);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
这里我们用User这个实体接收ajax传过来的参数,当然也可以这样写:
- public void addUser(String name , int age , HttpServletRequest request,HttpServletResponse response)
注意名字要与from表单传过来的参数名称一样,当然也可以不一样,不一样时的用法可以看我之前的文章.
User类:
- package gd.hz.springmvc.model;
-
- public class User {
- private String name ;
- private int age ;
-
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
-
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- }
- String result = "{\"name\":\"" + user.getName() + "\"}";
这句话,把传过来的数据拼成类json格式("key":"value"),这里要注意字符串里面的双引号不能用单引号表示,
- response.setContentType("application/json");
修改协议头,声明返回json格式.然后输出. 测试时可要注意年龄输入数字.
使用Spring内置的支持返回json.这个方法比较灵活,虽然复杂了一点,不过建议使用:
首先这里需要引入commons-fileupload-*.jar commons-io-*.jar commons-logging-*.jar jackson-annotations-*.jar jackson-core-*.jar jackson-databind-*.jar
看一下spring mvc的配置文件的配置
- <?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.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
-
- <context:component-scan base-package="gd.hz.springmvc.controller"></context:component-scan>
-
-
- <mvc:annotation-driven />
-
- <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
- <property name="mediaTypes">
- <map>
- <entry key="atom" value="application/atom+xml" />
- <entry key="html" value="text/html" />
- <entry key="json" value="application/json" />
- </map>
- </property>
- <property name="viewResolvers">
- <list>
- <bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
- <property name="prefix" value="/" />
- <property name="suffix" value=".jsp" />
- </bean>
- </list>
- </property>
- <property name="defaultViews">
- <list>
- <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" />
- </list>
- </property>
- </bean>
-
-
- <mvc:resources location="/script/" mapping="/script/**" />
- </beans>
这里我们声明的数据除text/html还有application/json和application/atom+xml.
先看一下我们的jsp页面json.jsp:
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <base href="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/">
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <script type="text/javascript" src="script/jquery-1.8.3.js"></script>
- <title>添加用户</title>
- <script type="text/javascript">
- $(function(){
- $("form :button").click(function(){
- $.ajax({
- type: "POST",
- url: "user/testJson",
- success:function(data){
- alert("名字:" + data.name + "年龄:" + data.age);
- }
- });
- });
- });
- </script>
- </head>
- <body>
- <form action="user/addUser" method="post">
- 用户名:<input type="text" id="name" name="name" /><br/>
- 年龄:<input type="text" id="age" name="age" />
- <input type="button" value="提交" />
- </form>
- </body>
- </html>
向user/testJson发送请求.成功后显示返回数据.
看一下Controller
- package gd.hz.springmvc.controller;
-
- import java.util.HashMap;
- import java.util.Map;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.ResponseBody;
-
- @Controller("userController")
- @RequestMapping("user")
- public class UserController {
-
- @RequestMapping("testJson")
- @ResponseBody
- public Map<String, Object> testJson() {
- System.out.println("testJson");
- Map<String, Object> modelMap = new HashMap<String, Object>();
- modelMap.put("name", "lfd");
- modelMap.put("age", "20");
- return modelMap;
- }
- }
@ResponseBody 将内容或对象作为 HTTP 响应正文返回,使用@ResponseBody将会跳过视图处理部分,将返回值写入输出流。
这里我放入的是简单的数据类型,也可以是复杂对象.集合.在页面可以用循环获取
再看一下使用ajax发送和接收数据:
还先看一下我们的jsp页面json2.jsp:
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- 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" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <base href="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/">
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <script type="text/javascript" src="script/jquery-1.8.3.js"></script>
- <script type="text/javascript" src="script/jquery.json-2.4.js"></script>
- <title>添加用户</title>
- <script type="text/javascript">
- $(function(){
- $.fn.serializeObject = function(){
- var o = {};
- var a = this.serializeArray();
- $.each(a, function(){
- if (o[this.name]) {
- if (!o[this.name].push) {
- o[this.name] = [o[this.name]];
- }
- o[this.name].push(this.value || '');
- }
- else {
- o[this.name] = this.value || '';
- }
- });
- return o;
- };
-
- $("#form :button").click(function(){
- var jsonuserinfo = $.toJSON($('#form').serializeObject());
- alert(jsonuserinfo);
- jQuery.ajax({
- type: 'POST',
- contentType: 'application/json',
- url: 'user/testJson2',
- data: jsonuserinfo,
- dataType: 'json',
- success: function(data){
- alert("名字:" + data.name + "年龄:" + data.age);
- },
- error: function(){
- alert("error");
- }
- });
- });
- });
- </script>
- </head>
- <body>
- <form action="user/addUser" method="post" id="form">
- 用户名:<input type="text" id="name" name="name" /><br/>
- 年龄:<input type="text" id="age" name="age" />
- <input type="button" value="提交" />
- </form>
- </body>
- </html>
这里除了使用jquery-1.8.3.js外还使用了一个插件jquery.json-2.4.js,大家可以上网下载
它的简单用法:
- var thing = { plugin: 'jquery-json', version: 2.4 };
-
- var encoded = $.toJSON( thing );
-
- var name = $.evalJSON( encoded ).plugin;
-
- var version = $.evalJSON(encoded).version;
下面这个方法是将表单中的数据组成json格式.
- $.fn.serializeObject = function(){
- var o = {};
- var a = this.serializeArray();
- $.each(a, function(){
- if (o[this.name]) {
- if (!o[this.name].push) {
- o[this.name] = [o[this.name]];
- }
- o[this.name].push(this.value || '');
- }
- else {
- o[this.name] = this.value || '';
- }
- });
- return o;
- };
Controller这边
- package gd.hz.springmvc.controller;
-
- import gd.hz.springmvc.model.User;
-
- import java.util.HashMap;
- import java.util.Map;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestBody;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.ResponseBody;
-
- @Controller("userController")
- @RequestMapping("user")
- public class UserController {
-
- @RequestMapping("testJson2")
- @ResponseBody
- public Map<String, Object> testJson2(@RequestBody User user) {
- System.out.println("testJson2");
- System.out.println(user.getName());
- System.out.println(user.getAge());
- Map<String, Object> modelMap = new HashMap<String, Object>();
- modelMap.put("name", user.getName());
- modelMap.put("age", user.getAge());
- return modelMap;
- }
- }
@RequestBody 将 HTTP 请求正文插入方法中,将请求体写入某个对象。
还是要注意,输入年龄时要是数值.祝大家测试成功.