作者:ssslinppp      时间:2015年5月26日 15:32:51

1. 摘要



本文讲解如何利用spring MVC框架,实现ajax异步请求以及json数据的返回。
使用到的技术主要如下:
  1. Ajax:使用JQuery 提供的ajax;==>需要引入jquery.min.js文件;
  2. Spring MVC;
  3. Json:提供两种方式返回json数据;

2. 项目结构






3. 前端



前台主界面:
文件位置:    浏览器界面:   

  1. <%@ page language="java" pageEncoding="UTF-8"%>
  2. <%
  3. String path = request.getContextPath();
  4. String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
  5. response.setHeader("Pragma", "no-cache");
  6. response.setHeader("Cache-Control", "no-cache");
  7. response.setDateHeader("Expires", 0);
  8. %>
  9. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  10. <html>
  11. <head>
  12. <title>SpringMVC+ajax+json</title>
  13. <script type="text/javascript">var basePath = "<%=basePath%>";</script>
  14. <%-- <link rel="stylesheet" type="text/css" href="<%=basePath%>js/easyui/demo.css"> --%>
  15. <script type="text/javascript" src="<%=basePath%>js/JQuery/jquery.min.js"></script>
  16. <script type="text/javascript" src="<%=basePath%>js/test/ajaxAndJson.js"></script>
  17. </head>
  18. <body>
  19. <div style="padding:5px 0;">
  20. <p>方式1</p>
  21. <a href="#" class="easyui-linkbutton" onclick="loadData1()" data-options="iconCls:'icon-add'">ajax异步获取json数据</a>
  22. </div>
  23. <div style="margin:10px 0 20px 0;"></div>
  24. <div style="padding:5px 0;">
  25. <p>方式2</p>
  26. <a href="#" class="easyui-linkbutton" onclick="loadData2()" data-options="iconCls:'icon-add'">ajax异步获取json数据</a>
  27. </div>
  28. </body>
  29. </html>

ajaxAndJson.js文件==>具体的ajax请求


  1. function loadData1() {
  2. var actionUrl = basePath + "test/testMVC1.action";
  3. var params = {
  4. "username" : 'zhangSan',
  5. 'passwd' : '12345678'
  6. };
  7. $.ajax({
  8. url : actionUrl,
  9. data : params,
  10. dataType : "json",
  11. cache : false,
  12. error : function(textStatus, errorThrown) {
  13. // $.messager.alert('错误', "系统请求错误: " + textStatus, 'error');
  14. alert("系统请求错误: " + textStatus);
  15. },
  16. success : function(data, textStatus) {
  17. // $.messager.alert('系统提示', data.username+data.passwd ,'info');
  18. alert(data.username+data.passwd );
  19. }
  20. });
  21. }
  22. function loadData2() {
  23. var actionUrl = basePath + "test/testMVC2.action";
  24. var params = {
  25. "username" : 'lisi',
  26. 'passwd' : '888888'
  27. };
  28. $.ajax({
  29. url : actionUrl,
  30. data : params,
  31. dataType : "json",
  32. cache : false,
  33. error : function(textStatus, errorThrown) {
  34. // $.messager.alert('错误', "系统请求错误: " + textStatus, 'error');
  35. alert("系统请求错误: " + textStatus);
  36. },
  37. success : function(data, textStatus) {
  38. // $.messager.alert('系统提示', data.Info+", "+data.userList[1].username ,'info');
  39. alert(data.Info+", "+data.userList[1].username);
  40. }
  41. });
  42. }



4. spring mvc配置文件



web.xml


  1. <web-app id="WebApp_ID" version="2.4"
  2. xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
  4. http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  5. <context-param>
  6. <param-name>contextConfigLocation</param-name>
  7. <param-value>classpath:applicationContext.xml</param-value>
  8. </context-param>
  9. <listener>
  10. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  11. </listener>
  12. <servlet>
  13. <servlet-name>mvc-dispatcher</servlet-name>
  14. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  15. <load-on-startup>1</load-on-startup>
  16. </servlet>
  17. <servlet-mapping>
  18. <servlet-name>mvc-dispatcher</servlet-name>
  19. <url-pattern>/rest/*</url-pattern>
  20. </servlet-mapping>
  21. </web-app>

spring-servlet.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context-3.0.xsd
  10. http://www.springframework.org/schema/mvc
  11. http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
  12. <!-- 扫描web包,应用Spring的注解 -->
  13. <context:component-scan base-package="com.ll.web"/>
  14. <!-- 配置视图解析器,将ModelAndView及字符串解析为具体的页面,默认优先级最低 -->
  15. <bean
  16. class="org.springframework.web.servlet.view.InternalResourceViewResolver"
  17. p:viewClass="org.springframework.web.servlet.view.JstlView"
  18. p:prefix="/jsp/"
  19. p:suffix=".jsp" />
  20. <!-- bean视图解析器 -->
  21. <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"
  22. p:order="10" />
  23. <!-- XMl及JSON视图解析器配置 -->
  24. <bean id="testMVC"
  25. class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
  26. <property name="renderedAttributes">
  27. <set>
  28. <value>userList</value>
  29. <value>Info</value>
  30. </set>
  31. </property>
  32. </bean>
  33. <mvc:annotation-driven/>
  34. </beans>

applicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context-3.0.xsd
  10. http://www.springframework.org/schema/tx
  11. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  12. http://www.springframework.org/schema/aop
  13. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
  14. <!-- 扫描类包,将标注Spring注解的类自动转化Bean,同时完成Bean的注入 -->
  15. <context:component-scan base-package="com.ll.service"/>
  16. <context:component-scan base-package="com.ll.dao"/>
  17. </beans>



5. 控制器



AjaxController.java

  1. package com.ll.web;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import org.springframework.stereotype.Controller;
  5. import org.springframework.ui.ModelMap;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.ResponseBody;
  8. import com.ll.model.Person;
  9. @Controller
  10. @RequestMapping(value = "/test")
  11. public class AjaxController {
  12. /**
  13. * 返回主页
  14. * @return
  15. */
  16. @RequestMapping(value = "/index.action")
  17. public String index() {
  18. return "index";
  19. }
  20. /**
  21. * 方式1:
  22. * 使用@ResponseBody方式返回json数据
  23. * @param username
  24. * @param passwd
  25. * @return
  26. */
  27. @ResponseBody
  28. @RequestMapping(value = "/testMVC1.action")
  29. public Person testAjax(String username,String passwd) {
  30. System.out.println("ajax-使用@ResponseBody方式返回json数据==>" + username + "(" + passwd + ")");
  31. return new Person(username,passwd);
  32. }
  33. /**
  34. * 方式2:
  35. * 使用MappingJacksonJsonView和bean视图解析器返回json数据
  36. * @param mm
  37. * @param username
  38. * @param passwd
  39. * @return
  40. */
  41. @RequestMapping(value = "/testMVC2.action")
  42. public String getFusionChartsData(ModelMap mm,String username,String passwd) {
  43. System.out.println("ajax-使用MappingJacksonJsonView和bean视图解析器返回json数据==>" + username + "(" + passwd + ")");
  44. Person p1 = new Person(username+"_1",passwd+"_*1");
  45. Person p2 = new Person(username+"_2",passwd+"_*2");
  46. List<Person> userList = new ArrayList<Person>();
  47. userList.add(p1);
  48. userList.add(p2);
  49. mm.addAttribute("userList", userList);
  50. mm.addAttribute("Info","测试spring MVC");
  51. return "testMVC";
  52. }
  53. }










【Spring学习笔记-MVC-5】利用spring MVC框架,实现ajax异步请求以及json数据的返回的更多相关文章

  1. 【Spring学习笔记-MVC-15.1】Spring MVC之异常处理=404界面

    作者:ssslinppp       异常处理请参考前篇博客:<[Spring学习笔记-MVC-15]Spring MVC之异常处理>http://www.cnblogs.com/sssl ...

  2. 【Spring学习笔记-MVC-13.2】Spring MVC之多文件上传

    作者:ssslinppp       1. 摘要 前篇文章讲解了单文件上传<[Spring学习笔记-MVC-13]Spring MVC之文件上传>http://www.cnblogs.co ...

  3. 【Spring学习笔记-MVC-18.1】Spring MVC实现RESTful风格-同一资源,多种展现:xml-json-html

    概要 要实现Restful风格,主要有两个方面要讲解,如下: 1. 同一个资源,如果需要返回不同的形式,如:json.xml等: 不推荐的做法: /user/getUserJson /user/get ...

  4. Spring学习笔记(四)-- Spring事务全面分析

    通过本系列的文章对Spring的介绍,我们对Spring的使用和两个核心功能IOC.AOP已经有了初步的了解,结合我个人工作的情况,因为项目是金融系 统.那对事务的控制是不可缺少的.而且是很严格的控制 ...

  5. Spring学习笔记(一)—— Spring介绍及入门案例

    一.Spring概述 1.1 Spring是什么 Spring是一个开源框架,是于2003年兴起的一个轻量级的Java开发框架, 由Rod Johnson 在其著作<Expert one on ...

  6. Spring学习笔记4—流程(Spring Web Flow)

    Spring Web Flow是Spring框架的子项目,作用是让程序按规定流程运行. 1 安装配置Spring Web Flow 虽然Spring Web Flow是Spring框架的子项目,但它并 ...

  7. Spring学习笔记(二)Spring基础AOP、IOC

    Spring AOP 1. 代理模式 1.1. 静态代理 程序中经常需要为某些动作或事件作下记录,以便在事后检测或作为排错的依据,先看一个简单的例子: import java.util.logging ...

  8. Spring学习笔记(四)—— Spring中的AOP

    一.AOP概述 AOP(Aspect Oriented Programming),即面向切面编程,可以说是OOP(Object Oriented Programming,面向对象编程)的补充和完善.O ...

  9. spring学习笔记(二)spring中的事件及多线程

    我们知道,在实际开发中为了解耦,或者提高用户体验,都会采用到异步的方式.这里举个简单的例子,在用户注册的sh时候,一般我们都会要求手机验证码验证,邮箱验证,而这都依赖于第三方.这种情况下,我们一般会通 ...

随机推荐

  1. react中为什么要使用immutable

    因为在react中,react的生命周期中的setState()之后的shouldComponentUpdate()阶段默认返回true,所以会造成本组件和子组件的多余的render,重新生成virt ...

  2. poj2892

    题解: 答案=后缀-前缀-1 如果被轰了,那么就时0 在一开始加入0,n+1,保证有前缀后缀 代码: #include<cstdio> #include<cmath> #inc ...

  3. L1-002 打印沙漏

    所谓“沙漏形状”,是指每行输出奇数个符号:各行符号中心对齐:相邻两行符号数差2:符号数先从大到小顺序递减到1,再从小到大顺序递增:首尾符号数相等. 给定任意N个符号,不一定能正好组成一个沙漏.要求打印 ...

  4. Swift网络封装库Moya中文手册之Authentication

    Authentication 安全验证可能有点复杂,一些网络请求需要认证,这里我们讨论两种常见的. Basic HTTP Auth HTTP auth是HTTP协议自带的用户名/密码验证.如果你使用的 ...

  5. 2.spring 学习

    1.spring简单工程搭建 http://www.cnblogs.com/yun965861480/p/6278193.html 2.spring数据源 http://www.cnblogs.com ...

  6. zabbix监控系统的应用---数据监控、导入模板、告警

    一.zabbix监控nginx服务 1)在server2中安装nginx服务 --->  rpm  -ivh  nginx-1.8.0-1.el6.ngx.x86_64.rpm 2)编辑配置文件 ...

  7. compile——生成ast

    刘涛 生成ast的函数是src/compiler/parser/index.js文件中的parse函数, 从这里入手,我们一起来看看一段html字符串,是如何一步步转换成抽象语法树的. 这一部分会涉及 ...

  8. uri 定义

    function path(){ $path=explode("/",$_SERVER['REQUEST_URI']); unset($path[(count($path)-1)] ...

  9. magento如何安装语言包

    1,先下安装,直接在www.magento.com(搜索chinese)官网获得下载密钥,然后在下载站点输入密钥就可以下载,下载完成后的安装包放到app/local文件夹下即可,到后台刷新一下: 2线 ...

  10. I.MX6 Linux Serial Baud Rate hacking

    /******************************************************************************** * I.MX6 Linux Seri ...