标签:
这篇文章实现三个功能:1.在jsp页面点击一个按钮,然后跳转到Action,在Action中把Emp(int id ,String salary,Data data)这个实体变成JSON格式返回到页面上。
2.在jsp页面点击第二个按钮,然后跳转到Action,在Action中把List<Emp>这个集合变成JSON格式返回到页面上。
3.在jsp页面点击第三个按钮,然后跳转到Action,
List<Emp> empList = new ArrayList<Emp>();
Map<String,Object> map;
map.put("total",empList.size());
map.put("rows",empList);
在Action中把 这个map变成JSON格式返回到页面上。
案例如下:
案例结构如下:
所用的代码文件:com.guigu.shen.Action11(实体类Emp.java;控制器类userAction.java;配置文件springmvc_11.xml);web.xml;bean2json.jsp;
第一步:先写bean2json.jsp
<%@ 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> <base href="<%=basePath%>"> <title>My JSP ‘index.jsp‘ starting page</title> <script type="text/javascript" src="js/jquery-1.8.2.js"></script> </head> <body> <input type="button" value="Emp转JSON" /></p> <input type="button" value="List<Emp>转JSON" /></p> <input type="button" value="Map<String,Object>"转JSON"/></p> <!--Emp转JSON --> <script type="text/javascript"> $(":button:first").click( function() { var url="${pageContext.request.contextPath}/emp/bean2json.action"; var sendData=null; //第一个参数是请求的网址,第二个参数是返回的状态,第三个是回调函数 $.post(url,sendData,function(backData,textStaut,ajax){ alert(ajax.responseText); }); } ); </script> <!-- Map<String,Object>转JSON 这个非常重要--> <script type="text/javascript"> $(":button:last").click(function(){ var url = "${pageContext.request.contextPath}/emp/map2json.action"; var sendData = null; $.post(url,sendData,function(backData,textStaut,ajax){ alert(ajax.responseText); }); }); </script> <!-- List<Emp>转JSON --> <script type="text/javascript"> $(":button:eq(1)").click(function(){ var url = "${pageContext.request.contextPath}/emp/listbean2json.action"; var sendData = null; $.post(url,sendData,function(backData,textStaut,ajax){ alert(ajax.responseText); }); }); </script> </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_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>SpringMvc_10day_self</display-name> <!-- Spring提供了一个Filter专门用来解决Post提交中文的乱码问题 --> <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> <servlet> <!--这个名字可以随便取得,但是这个名字取了之后,以后在 WEB-INF下面创建SpirngMVC的配置文件是,命名必须以这个开头, 所以这里取名叫做DispatcherServlet,那么之后的xml文件取名必须为DispatcherServlet-servlet.xml(一个字都不能差) --> <servlet-name>DispatcherServlet</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 通知DispatcherServlet去指定目录下找到springmvc.xml配置文件 --> <!-- 注意这里的 <param-name>contextConfigLocation</param-name>一个字母都不能有错 一旦有错就会去WEB-INF下面去找 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
第三步:写spring.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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd" > <import resource="com/guigu/shen/Action11/springmvc_11.xml"/> </beans>
第四步:springmvc_11.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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-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="com.guigu.shen.Action11"/> <!-- 基于注解的映射器(可选) 这个类和以前的xml方式的类不同,专门是注解用的 --> <!-- 使用JSON的所要做的事情: 1)导入jackson-core-asl-1.9.11.jar和jackson-mapper-asl-1.9.11.jar 2)在业务方法的返回值和权限之间使用@ResponseBody注解表示返回值对象需要转成JSON文本 3)在spring.xml配置文件中编写如下代码: <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/> </list> </property> </bean> --> <!-- 注册适配器 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/> </list> </property> </bean> </beans>
第五步:写com.guigu.shen.Action11下面的Emp.java和UserAction.java
package com.guigu.shen.Action11; import java.util.Date; public class Emp { private Integer id; private String username; private Double salary; private Date hiredate; public Emp(){} public Emp(Integer id, String username, Double salary, Date hiredate) { this.id = id; this.username = username; this.salary = salary; this.hiredate = hiredate; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Double getSalary() { return salary; } public void setSalary(Double salary) { this.salary = salary; } public Date getHiredate() { return hiredate; } public void setHiredate(Date hiredate) { this.hiredate = hiredate; } }
package com.guigu.shen.Action11; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.omg.CORBA.PUBLIC_MEMBER; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; /** * * 请求路径可以拆分为:根模块的名字+分模块的名字 就是相当于当访问http://127.0.0.1:8080:项目名/user/register时就会进入到 registerMethod方法。 */ @Controller @RequestMapping(value="/emp")//根模块的请求名字 public class UserAction { //bean转成json @RequestMapping(method=RequestMethod.POST,value="/bean2json")//分模块的请求名字 /* * @ResponseBody Emp 表示让springmvc将Emp对象转成JSON文本 * */ public @ResponseBody Emp EmptoJson() { Emp emp=new Emp(1, "伤", 111.1, new Date()); return emp; } //list转成Json @RequestMapping(method=RequestMethod.POST,value="/listbean2json")//分模块的请求名字 public @ResponseBody List<Emp> listbenatoJson() { List<Emp> empList = new ArrayList<Emp>(); empList.add(new Emp(1,"伤",7000D,new Date())); empList.add(new Emp(2,"伤",8000D,new Date())); empList.add(new Emp(3,"伤",9000D,new Date())); return empList; } //map转成json @RequestMapping(value="/map2json") public @ResponseBody Map<String,Object> map2json() throws Exception{ List<Emp> empList = new ArrayList<Emp>(); empList.add(new Emp(1,"伤",7000D,new Date())); empList.add(new Emp(2,"伤",8000D,new Date())); empList.add(new Emp(3,"伤",9000D,new Date())); Map<String,Object> map = new LinkedHashMap<String,Object>(); map.put("total",empList.size()); map.put("rows",empList); return map; } }
最后一步测试:
按钮如下:
点击“Emp转JSon”效果如下:
点击“List<Emp>转JSON”效果如下:
点击"Map<Strin,Object>"效果如下:
Map<Strin,Object>这个是最重要的。
21SpringMvc_异步发送表单数据到Bean,并响应JSON文本返回(这篇可能是最重要的一篇了)
标签:
原文地址:http://www.cnblogs.com/shenxiaoquan/p/5756336.html