这篇文章实现三个功能: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.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/mvchttp://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.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/mvchttp://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.jar2)在业务方法的返回值和权限之间使用@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文本返回(这篇可能是最重要的一篇了)...相关推荐

  1. php 发送表单数据,php - 将表单数据发送到会话变量 - SO中文参考 - www.soinside.com...

    我有一个页面,表格需要通过邮寄发送.我的htaccess在其中重定向导致后期数据丢失,因此我想将这些数据放入会话变量中以便由另一个页面拾取. 表单页面下面的会话变量"favcolor&quo ...

  2. request.form以及postman发送表单数据

    @app.route('/command', methods=['POST']) def command():bcmd = bytes.fromhex(request.form['cmd'])prin ...

  3. 【ASP.NET Web API教程】5.2 发送HTML表单数据:URL编码的表单数据

    注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本系列教程,请先看前面的内容. 5.2 Sending HTML Form Data 5.2 发送HTML表单数据 本文引 ...

  4. WebApi发送HTML表单数据:文件上传与多部分MIME

    5.3 Sending HTML Form Data 5.3 发送HTML表单数据(2) 本文引自:http://www.cnblogs.com/r01cn/archive/2012/12/20/28 ...

  5. (转)WebApi发送HTML表单数据:文件上传与多部分MIME

    5.3 Sending HTML Form Data 5.3 发送HTML表单数据(2) 本文引自:http://www.cnblogs.com/r01cn/archive/2012/12/20/28 ...

  6. 如何发送HTML表单数据

    多数时候,HTML表单的目的只是为了把数据发给服务器,之后服务器再处理这些数据并发送响应给用户.虽然看起来挺简单的,但我们还是得注意一些事情以确保传送的数据不会破坏服务器.或者给你的用户制造麻烦. 数 ...

  7. C# 后台发送Post Get请求 Json数据或表单数据

    Http请求类 public class HttpResponse{#region Static Fieldprivate static readonly string DefaultUserAgen ...

  8. ajax异步实现表单的无刷新验证

    在 实现ajax异步实现表单的无刷新验证之前我们先要了解什么是异步什么是同步 "同步模式"就是上一段的模式,后一个任务等待前一个任务结束,然后再执行,程序的执行顺序与任务的排列顺序 ...

  9. php 保存表单数据,使用jquery和php自动保存表单数据

    我对PHP非常好,但是使用jQuery的总菜单,并且卡在自动保存表单数据中. 自动保存功能在dummy.php中每30秒调用一次.我正在将用于处理的序列化表单数据( – >数据库)发送到save ...

最新文章

  1. Spark Streaming实践和优化
  2. ajax跨域原理以及解决方案
  3. Netty 高性能特性
  4. JAVASE内测试题
  5. 关于keil环境的 三个红点(备忘)
  6. MySQL数据检索+查询+全文本搜索
  7. 协同遗漏的效果–使用简单的NIO客户端/服务器测量回送延迟
  8. IIS 7.0探索用于 Windows Vista 的 Web 服务器和更多内容
  9. java 日期只计算年月日大小_Java按自然月计算两个日期相差的年月日?
  10. “卢十瓦”疯狂预热红米Note 8 10W“快”充不会再有了
  11. java property类_Java之Property类使用
  12. 无法显示添加端口对话框 服务器,服务器添加开放端口
  13. NLP硬核入门-Seq2Seq和Attention机制
  14. Delphi中Hash表的使用方法!
  15. easyui 提示框组件_jQuery EasyUI 教程-Tooltip(提示框)
  16. 企业如何布局数字化营销,打造私域运营闭环实现增长?
  17. 百度网盘链接怎么同步更新、百度网盘链接同步、百度网盘分享同步更新、百度网盘怎么同步更新、百度网盘资源同步更新、百度网盘分享文件同步更新、百度网盘好友分享同步更新、百度网盘共享文件同步更新...
  18. 什么是熔断? 熔断有哪几种状态 ?断路器的工作原理
  19. PHP之依赖注入容器pimple
  20. Java学习之编程入门

热门文章

  1. 【Maven】win10系统安装Maven
  2. 【Oracle】to_char技巧
  3. 浏览器的同源策略与跨域问题的解决方案
  4. SpringBoot-@ControllerAdvice 拦截异常并统一处理
  5. java-png图片压缩,解决png图片压缩后背景变黑问题
  6. php reader oleread,请问用phpExcelReader方式,excel文件名字可以是中文吗?
  7. android新运行时权限
  8. 多组input文件,每组 multiple选择多张图片上传可增删其中任意一张图片,用formData对象实现(ajax,sync: false同步)
  9. vscode jupyter补全_Cern ROOT 在jupyter里的使用
  10. Android 8.0系统源码分析--开篇