此篇文章的讲解是基于前几篇文章的内容,如果大家有看不懂的地方可以看前几篇的内容.
spring mvc返回json数据可方法常用的有
- 直接PrintWriter 输出
- 使用Spring内置的支持
下面我分别对上面的两种方法进行讲解:注意这篇文章的讲解使用的是spring3.2版本,此版本与spring 3.0的配置有少许不同,希望大家注意,同时我使用的是jquery做演示.
首先讲解直接PrintWriter 输出,这个是最简单的,但是不可以使用java的复杂对象.
没有什么需要配置的,直接请求我们的ajax请求页面json.jsp.
- <%@pagelanguage="java"contentType="text/html;charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <basehref="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/">
- <metahttp-equiv="Content-Type"content="text/html;charset=UTF-8">
- <scripttype="text/javascript"src="script/jquery-1.8.3.js"></script>
- <title>添加用户</title>
- <scripttype="text/javascript">
- $(function(){
- $("form:button").click(function(){
- varname=$("#name").val();
- varage=$("#age").val();
- $.ajax({
- type:"POST",
- url:"user/addUser",
- data:{name:name,age:age},
- success:function(data){
- alert("名字:"+data.name+"年龄:"+data.age);
- }
- });
- });
- });
- </script>
- </head>
- <body>
- <formaction="user/addUser"method="post">
- 用户名:<inputtype="text"id="name"name="name"/><br/>
- 年龄:<inputtype="text"id="age"name="age"/>
- <inputtype="button"value="提交"/>
- </form>
- </body>
- </html>
给提示按钮添加点击事件,当提交表单时获取用户名name,和年龄age,以post的方式提交表user/addUser,并把服务器返回的数据显示出来,这里要注意JSP页面头上最好加上
- <basehref="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/">
使用绝对路径,一切从根目录开始找起,要不然会因为路径问题,而且很烦,js也要声明为spring mvc不要拦截,这里之前文章有说过
Controller:
- packagegd.hz.springmvc.controller;
- importjava.io.IOException;
- importjava.io.PrintWriter;
- importjavax.servlet.http.HttpServletRequest;
- importjavax.servlet.http.HttpServletResponse;
- importgd.hz.springmvc.model.User;
- importorg.springframework.stereotype.Controller;
- importorg.springframework.web.bind.annotation.RequestMapping;
- @Controller("userController")
- @RequestMapping("user")
- publicclassUserController{
- //ajax请求一
- @RequestMapping("addUser")
- publicvoidaddUser(Useruser,HttpServletRequestrequest,
- HttpServletResponseresponse){
- //这里不能用单引号,无效,死的心都有
- System.out.println("过来了");
- Stringresult="{\"name\":\""+user.getName()+"\"}";
- PrintWriterout=null;
- System.out.println(result);
- response.setContentType("application/json");
- try{
- out=response.getWriter();
- out.write(result);
- }catch(IOExceptione){
- e.printStackTrace();
- }
- }
- }
这里我们用User这个实体接收ajax传过来的参数,当然也可以这样写:
- publicvoidaddUser(Stringname,intage,HttpServletRequestrequest,HttpServletResponseresponse)
注意名字要与from表单传过来的参数名称一样,当然也可以不一样,不一样时的用法可以看我之前的文章.
User类:
- packagegd.hz.springmvc.model;
- publicclassUser{
- privateStringname;
- privateintage;
- publicStringgetName(){
- returnname;
- }
- publicvoidsetName(Stringname){
- this.name=name;
- }
- publicintgetAge(){
- returnage;
- }
- publicvoidsetAge(intage){
- this.age=age;
- }
- }
- Stringresult="{\"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的配置文件的配置
- <?xmlversion="1.0"encoding="UTF-8"?>
- <beansxmlns="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-scanbase-package="gd.hz.springmvc.controller"></context:component-scan>
- <!--将上面两个注解和并-->
- <mvc:annotation-driven/>
- <beanclass="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
- <propertyname="mediaTypes">
- <map>
- <entrykey="atom"value="application/atom+xml"/>
- <entrykey="html"value="text/html"/>
- <entrykey="json"value="application/json"/>
- </map>
- </property>
- <propertyname="viewResolvers">
- <list>
- <beanclass="org.springframework.web.servlet.view.BeanNameViewResolver"/>
- <beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <propertyname="viewClass"value="org.springframework.web.servlet.view.JstlView"></property>
- <propertyname="prefix"value="/"/>
- <propertyname="suffix"value=".jsp"/>
- </bean>
- </list>
- </property>
- <propertyname="defaultViews">
- <list>
- <beanclass="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>
- </list>
- </property>
- </bean>
- <!--声明DispatcherServlet不要拦截下面声明的目录-->
- <mvc:resourceslocation="/script/"mapping="/script/**"/>
- </beans>
这里我们声明的数据除text/html还有application/json和application/atom+xml.
先看一下我们的jsp页面json.jsp:
- <%@pagelanguage="java"contentType="text/html;charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <basehref="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/">
- <metahttp-equiv="Content-Type"content="text/html;charset=UTF-8">
- <scripttype="text/javascript"src="script/jquery-1.8.3.js"></script>
- <title>添加用户</title>
- <scripttype="text/javascript">
- $(function(){
- $("form:button").click(function(){
- $.ajax({
- type:"POST",
- url:"user/testJson",
- success:function(data){
- alert("名字:"+data.name+"年龄:"+data.age);
- }
- });
- });
- });
- </script>
- </head>
- <body>
- <formaction="user/addUser"method="post">
- 用户名:<inputtype="text"id="name"name="name"/><br/>
- 年龄:<inputtype="text"id="age"name="age"/>
- <inputtype="button"value="提交"/>
- </form>
- </body>
- </html>
向user/testJson发送请求.成功后显示返回数据.
看一下Controller
- packagegd.hz.springmvc.controller;
- importjava.util.HashMap;
- importjava.util.Map;
- importorg.springframework.stereotype.Controller;
- importorg.springframework.web.bind.annotation.RequestMapping;
- importorg.springframework.web.bind.annotation.ResponseBody;
- @Controller("userController")
- @RequestMapping("user")
- publicclassUserController{
- @RequestMapping("testJson")
- @ResponseBody
- publicMap<String,Object>testJson(){
- System.out.println("testJson");
- Map<String,Object>modelMap=newHashMap<String,Object>();
- modelMap.put("name","lfd");
- modelMap.put("age","20");
- returnmodelMap;
- }
- }
@ResponseBody 将内容或对象作为 HTTP 响应正文返回,使用@ResponseBody将会跳过视图处理部分,将返回值写入输出流。
这里我放入的是简单的数据类型,也可以是复杂对象.集合.在页面可以用循环获取
再看一下使用ajax发送和接收数据:
还先看一下我们的jsp页面json2.jsp:
- <%@pagelanguage="java"contentType="text/html;charset=UTF-8"
- pageEncoding="UTF-8"%>
- <%
- Stringpath=request.getContextPath();
- StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <basehref="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/">
- <metahttp-equiv="Content-Type"content="text/html;charset=UTF-8">
- <scripttype="text/javascript"src="script/jquery-1.8.3.js"></script>
- <scripttype="text/javascript"src="script/jquery.json-2.4.js"></script>
- <title>添加用户</title>
- <scripttype="text/javascript">
- $(function(){
- $.fn.serializeObject=function(){
- varo={};
- vara=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||'';
- }
- });
- returno;
- };
- $("#form:button").click(function(){
- varjsonuserinfo=$.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>
- <formaction="user/addUser"method="post"id="form">
- 用户名:<inputtype="text"id="name"name="name"/><br/>
- 年龄:<inputtype="text"id="age"name="age"/>
- <inputtype="button"value="提交"/>
- </form>
- </body>
- </html>
这里除了使用jquery-1.8.3.js外还使用了一个插件jquery.json-2.4.js,大家可以上网下载
它的简单用法:
- varthing={plugin:'jquery-json',version:2.4};
- varencoded=$.toJSON(thing);
- //'{"plugin":"jquery-json","version":2.4}'
- varname=$.evalJSON(encoded).plugin;
- //"jquery-json"
- varversion=$.evalJSON(encoded).version;
下面这个方法是将表单中的数据组成json格式.
- $.fn.serializeObject=function(){
- varo={};
- vara=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||'';
- }
- });
- returno;
- };
Controller这边
- packagegd.hz.springmvc.controller;
- importgd.hz.springmvc.model.User;
- importjava.util.HashMap;
- importjava.util.Map;
- importorg.springframework.stereotype.Controller;
- importorg.springframework.web.bind.annotation.RequestBody;
- importorg.springframework.web.bind.annotation.RequestMapping;
- importorg.springframework.web.bind.annotation.ResponseBody;
- @Controller("userController")
- @RequestMapping("user")
- publicclassUserController{
- @RequestMapping("testJson2")
- @ResponseBody
- publicMap<String,Object>testJson2(@RequestBodyUseruser){
- System.out.println("testJson2");
- System.out.println(user.getName());
- System.out.println(user.getAge());
- Map<String,Object>modelMap=newHashMap<String,Object>();
- modelMap.put("name",user.getName());
- modelMap.put("age",user.getAge());
- returnmodelMap;
- }
- }
@RequestBody 将 HTTP 请求正文插入方法中,将请求体写入某个对象。
还是要注意,输入年龄时要是数值.祝大家测试成功.