21SpringMvc_异步发送表单数据到Bean,并响应JSON文本返回(这篇可能是最重要的一篇了)

这篇文章实现三个功能: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>这个是最重要的。

时间: 2024-08-09 13:40:37

21SpringMvc_异步发送表单数据到Bean,并响应JSON文本返回(这篇可能是最重要的一篇了)的相关文章

异步发送表单数据到JavaBean,并响应JSON文本返回

1)  提交表单后,将JavaBean信息以JSON文本形式返回到浏览器 <form> 编号:<input type="text" name="id" value="1"/><br/> 姓名:<input type="text" name="name" value="哈哈"/><br/> 薪水:<input type=&q

phpcms实现验证码以及异步提交表单数据

在phpcms网站中使用验证码我们要考虑前端模板页面中如何调用验证码和后台程序中如何验证两个方面: 一.在模板中,调用验证码的代码如下: 1 <label for="code">验证码</label> 2 <input type="text" id="code" name="code" size="10"> 3 {form::checkcode('code_img', '

JavaScript实现ajax发送表单数据

前端样式: <style> .model{ position: fixed; top: 0px; left: 0px; bottom: 0px; right: 0px; background-color: white; } .hide{ display: none; } </style> 前端html代码: <div><a onclick="show_form();">添加</a></div> <div cl

通过FormData对象可以组装一组用 [XMLHttpRequest]发送请求的键/值对,它可以更灵活方便的发送表单数据。

工作记录用 1 大概页面,点击选择按钮,选择文件,填写备注并可以上传前预览,然后点击上传按钮开始上传 2 html+js代码 <h2>Test</h2> <div id="fileList"></div> <span id="file_ct" style="display:none"><input id="file_input" accept="Ima

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

注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本系列教程,请先看前面的内容. 5.2 Sending HTML Form Data 5.2 发送HTML表单数据 本文引自:http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-1 By Mike Wasson|June 15, 2012 作者:Mike Wasson | 日期:2012-6-15 Part

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

5.3 Sending HTML Form Data5.3 发送HTML表单数据(2) 本文引自:http://www.cnblogs.com/r01cn/archive/2012/12/20/2826230.html By Mike Wasson|June 21, 2012作者:Mike Wasson | 日期:2012-6-21 Part 2: File Upload and Multipart MIME第2部分:文件上传与多部分MIME This tutorial shows how to

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

5.3 Sending HTML Form Data5.3 发送HTML表单数据(2) 本文引自:http://www.cnblogs.com/r01cn/archive/2012/12/20/2826230.html By Mike Wasson|June 21, 2012作者:Mike Wasson | 日期:2012-6-21 Part 2: File Upload and Multipart MIME第2部分:文件上传与多部分MIME This tutorial shows how to

如何发送HTML表单数据

多数时候,HTML表单的目的只是为了把数据发给服务器,之后服务器再处理这些数据并发送响应给用户.虽然看起来挺简单的,但我们还是得注意一些事情以确保传送的数据不会破坏服务器.或者给你的用户制造麻烦. 数据会到哪里去 关于客户端/服务器架构 整个web都是基于一种基本的客户端/服务器架构,该架构可以归纳如下: 一个客户端(通常是Web浏览器)使用HTTP协议发送一个请求给服务器(通常是web服务器程序,譬如Apache, Nginx, IIS, Tomcat等等),而服务器则以相同的协议响应这个请求

使用jQuery实现跨域提交表单数据

我们在WEB开发中有时会遇到这种情况,比如要从A网站收集用户信息,提交给B网站处理,这个时候就会涉及到跨域提交数据的问题.本文将给您介绍如何使用jQuery来实现异步跨域提交表单数据. 在jQuery中,我们使用json数据类型,通过getJSON方法来实现从服务端获取或发送数据,而当要向不同远程服务器端提交或者获取数据时,要采用jsonp数据类型.使用这种类型的话,会创建一个查询字符串参数 callback=? ,这个参数会加在请求的URL后面.服务器端应当在JSON数据前加上回调函数名,以便