原文地址:http://liuzidong.iteye.com/blog/1069343

注意这个例子要使用jQuery,但是jquery文件属于静态的资源文件,所以要在springMVC中设置静态资源访问

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_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>SpringMVCFile</display-name>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<!-- 配置前台分发器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 扫描使用springmvc配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

springMVC的配置文件

<?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:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 扫描包裹,我们完全使用注释定义 Bean 并完成 Bean 之间装配: -->
<context:component-scan base-package="com.fileUpDown" />
<!-- 解决了@Controller注解的使用前提配置。 -->
<mvc:annotation-driven />
<!-- 配置对静态资源的处理 -->
<!-- mapping是映射路径,location是本地属性就是webcontent下的目录,web-inf可能访问不到 -->
<mvc:resources mapping="/file/**" location="/fileHome/" /> <!-- 定义view视图解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
<!-- 设置文件上传的一些属性 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="UTF-8" />
</beans>

前台的界面

<%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<%-- <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery/jquery-1.4.4.min.js"></script> --%>
<script type="text/javascript" src="${pageContext.request.contextPath}/jquery-1.11.0.min.js"></script>
<title>Spring MVC - jQuery 整合教程</title>
</head>
<body>
<h3>Spring MVC - jQuery 整合教程</h3>
<h4>AJAX version</h4>
<p>Demo 1 计算并返回值</p>
<div style="border: 1px solid #ccc; width: 250px;">
Add Two Numbers: <br/>
<input id="inputNumber1" type="text" size="5"> +
<input id="inputNumber2" type="text" size="9">
<input type="submit" id="demo1" value="Add" /> <br/>
Sum: <br>
<span id="sum">(Result will be shown here)</span>
</div>
<hr><br>
<p>Demo 2 获取一个对象</p>
<div style="border: 1px solid #ccc; width: 250px;">
<select id="userId">
<c:forEach var="index" begin="1" end="5" step="1">
<option value="${index}">${index}</option>
</c:forEach>
</select>
<input type="submit" id="demo2" value="Get" /> <br/>
<span id="info">(Result will be shown here)</span>
</div>
<hr><br>
<p>Demo 3 返回List集合对象</p>
<div style="border: 1px solid #ccc; width: 250px;">
<input type="submit" id="demo3" value="Get List User" /> <br/>
<span id="listInfo">(Result will be shown here)</span>
</div>
<hr><br>
<p>Demo 4 返回Map集合对象</p>
<div style="border: 1px solid #ccc; width: 250px;">
<input type="submit" id="demo4" value="Get Map User" /> <br/>
<span id="mapInfo">(Result will be shown here)</span>
</div>
<hr><br>
<a href="${pageContext.request.contextPath}/index.jsp">返回</a>
<hr><br> <script type="text/javascript">
$(function() {
$("#demo1").click(function(){
//当demo1发生点击事件后,对/main/ajax/add.do发送请求,把传递的数据以json的形式传递,
//请求完成后使用function(data)函数,把结果显示到页面上来
$.post("${pageContext.request.contextPath}/main/ajax/add.do",
{inputNumber1: $("#inputNumber1").val(),
inputNumber2: $("#inputNumber2").val()
}, function(data){
$("#sum").replaceWith('<span id="sum">'+ data + '</span>');
});
}); $("#demo2").click(function(){
var userId = $("#userId").val();
$.post("${pageContext.request.contextPath}/main/ajax/getUser/"+userId+".do",
null,
function(data){
var info = "姓名: " + data.name+",年龄: " + data.age + ",地址: " + data.address + ",性别: " + (data.sex == 1 ? "男" : "女")+",密码: " + data.password;
$("#info").html(info);
});
}); $("#demo3").click(function(){
$.post("${pageContext.request.contextPath}/main/ajax/userList.do",
null,
function(data){
var info = '';
$.each(data,function(index,entity) {
info += "姓名: " + entity.name+",年龄: " + entity.age + ",地址: " + entity.address + ",性别: " + (entity.sex == 1 ? "男" : "女")+",密码: " + entity.password+"<br>";
});
$("#listInfo").html(info);
});
}); $("#demo4").click(function(){
$.post("${pageContext.request.contextPath}/main/ajax/userMap.do",
null,
function(map){
var info = '';
$.each(map,function(key,values) {
info += "key="+key+"<br>";
$(values).each(function(){
info += "姓名: " + this.name+",年龄: " + this.age + ",地址: " + this.address + ",性别: " + (this.sex == 1 ? "男" : "女")+",密码: " + this.password+"<br>";
}); });
$("#mapInfo").html(info);
});
}); });
</script>
</body>
</html>

com.fileUpDown包下的action jqueryJsonAction.Java

package com.fileUpDown;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import com.springMVC.javaBean.User; @Controller
@RequestMapping("/main/ajax")
public class jqueryJsonAction {
/**
* 根据映射跳转到指定的页面
*/
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String getAjaxAddPage() {
// 跳转到ajax-add-page
return "ajax-add-page";
} /**
* 提交表单并进行运算.
*/
@RequestMapping(value = "/add", method = RequestMethod.POST)
public @ResponseBody Integer add(@RequestParam(value = "inputNumber1", required = true) Integer inputNumber1,
@RequestParam(value = "inputNumber2", required = true) Integer inputNumber2) {
// 实现运算
Integer sum = inputNumber1 + inputNumber2;
System.out.println("sum: " + sum);
// @ResponseBody 会自动的将返回值转换成JSON格式
// 但是你必须添加jackson的jar包!!!
return sum;
} @RequestMapping(value = "/getUser/{userId}", method = RequestMethod.POST)
/**
* @ResponseBody注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,
* 写入到Response对象的body数据区 使用的时候Controller返回的不是界面的时候,是json或者xml
*/
/**
* 当使用@RequestMapping URI template 样式映射时, 即 someUrl/{paramId},
* 这时的paramId可通过 @Pathvariable注解绑定它传过来的值到方法的参数上。
*/
public @ResponseBody User getUser(@PathVariable("userId") String userId) {
System.out.println("根据ID获取用户对象: " + userId);
Map<String, User> users = new HashMap<String, User>();
users.put("1", new User("123456", "李逵", "123", "成都市", "1", 23));
users.put("2", new User("565676", "张三", "123", "北京市", "2", 53));
users.put("3", new User("325566", "李四", "123", "河南省", "2", 93));
users.put("4", new User("989654", "刘邦", "123", "蒙古包", "1", 13));
users.put("5", new User("234444", "王熙凤", "123", "成都市", "1", 43));
return users.get(userId);
} @RequestMapping(value = "/userList", method = RequestMethod.POST)
public @ResponseBody List<User> getUsers() {
List<User> users = new ArrayList<User>();
users.add(new User("123456", "李逵", "123", "成都市", "1", 23));
users.add(new User("123457", "李四", "124", "北京市", "2", 53));
users.add(new User("123458", "李三", "125", "河南市", "0", 73));
users.add(new User("123459", "李五", "126", "大路市", "3", 93));
return users;
}
@RequestMapping(value="/userMap",method = RequestMethod.POST)
public @ResponseBody Map<String,User> getMap(){
Map<String,User> map = new HashMap<String,User>();
for(int i=0;i<4;i++){
map.put(""+i, new User("123456", "李逵", "123", "成都市", "1", i+23));
}
return map;
}
}

javaBean对象

package com.springMVC.javaBean;

public class User {
private String num;
private String name;
private String password;
private String address;
private String sex;
private int age;
public User(String num, String name, String password, String address, String sex, int age) {
super();
this.num = num;
this.name = name;
this.password = password;
this.address = address;
this.sex = sex;
this.age = age;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
} }

springMVC框架下返回json格式的对象,list,map的更多相关文章

  1. 总结的一些json格式和对象/String/Map/List等的互转工具类

    总结的一些json格式和对象/String/Map/List等的互转工具类,有需要的可以看看,需要引入jackson-core-asl-1.7.1.jar.jackson-jaxrs-1.7.1.ja ...

  2. SpringMVC框架下实现JSON(类方法中回传数据到jsp页面,使用jQuery方法回传)

    JSON的实现,即将需要的数据回传到jsp页面: 1>.加入实现Json的三个架包到lib中:2>.目标方法上边加入注解,需要返回的值3>.在jsp页面中书写jQuery方法: ec ...

  3. Spring MVC返回json格式

    在使用SpringMVC框架直接返回json数据给client时,不同的版本号有差异. 以下介绍两种类型的版本号怎样配置. 注意:这两种方法均已验证通过. 1.Spring3.1.x版本号 1.1 d ...

  4. (转)springMVC框架下JQuery传递并解析Json数据

    springMVC框架下JQuery传递并解析Json数据 json作为一种轻量级的数据交换格式,在前后台数据交换中占据着非常重要的地位.Json的语法非常简单,采用的是键值对表示形式.JSON 可以 ...

  5. SpringMVC通过实体类返回json格式的字符串,并在前端显示

    一.除了搭建springmvc框架需要的jar包外,还需要这两个jar包 jackson-core-asl-1.9.2.jar和jackson-mapper-asl-1.9.2.jar 二.web,. ...

  6. 如何解决jersey框架中以json格式返回数组,当数组中元素一个时json格式不对

    原文地址:http://www.cnblogs.com/swpk/p/3566536.html?utm_source=tuicool jersey 是oracle 出的一个较好的REST框架.使用此框 ...

  7. JSon_零基础_005_将po(bean)对象集合List转换为JSon格式的对象字符串,返回给界面

    将po(bean)对象集合List转换为JSon格式的对象字符串,返回给界面 导入jar包: 编写:po(bean)代码: package com.west.webcourse.po; /** * 第 ...

  8. JSon_零基础_005_将po(bean)对象转换为JSon格式的对象字符串,返回给界面

    将po(bean)对象转换为JSon格式的对象字符串,返回给界面 导入jar包: 编写po(bean)类: package com.west.webcourse.po; /** * 第01步:编写be ...

  9. JSon_零基础_004_将Set集合对象转换为JSon格式的对象字符串,返回给界面

    将Set集合对象转换为JSon格式的对象字符串,返回给界面 需要导入的jar包: 编写:servlet: package com.west.webcourse.servlet; import java ...

随机推荐

  1. ElasticSearch 6.2.3 Windows10 安装

    一.安装Es 1.安装java,最新版本的ElasticSearch 需要java8 版本,因此需要先去Oracle官网下载jdk,下载之后就直接安装: 2.安装过程中将其安装目录copy下来:C:\ ...

  2. 在web应用中使用文件

    使用HTML5 DOM新增的File API,现在可以让网页要求用户选择本地文件,并且读取这些文件的信息了.选择的方式既可以是HTML<input> 元素,也可以是拖拽 . 你可以在chr ...

  3. Node.js学习笔记(一) --- HTTP 模块、URL 模块、supervisor 工具

    一.Node.js创建第一个应用 如果我们使用 PHP 来编写后端的代码时,需要 Apache 或者 Nginx 的 HTTP 服务器, 来处理客户端的请求相应.不过对 Node.js 来说,概念完全 ...

  4. SQL Join 语句

    SQL Join 语句 SQL 中每一种连接操作都包括一个连接类型和连接条件. 连接类型 决定了如何处理连接条件不匹配的记录. 连接类型 返回结果 inner join 只包含左右表中满足连接条件的记 ...

  5. RegExp.prototype.exec()使用技巧

    RegExp.prototype.exec() exec() 方法在一个指定字符串中执行一个搜索匹配.返回一个结果数组或 null. 如果你只是为了判断是否匹配(true或 false),可以使用 R ...

  6. CSS的伪类 :before 和 :after

    CSS 有两个说不上常用的伪类 :before 和 :after,偶尔会被人用来添加些自定义格式什么的,但是它们的功用不仅于此.前几天发现了 Creative Link Effects 这个非常有意思 ...

  7. iview中关于table组件内放入Input会失去焦点

    table里面的数据是一个数组,父组件传入的.子组件是截图的内容.当每个input框数据发生变化时,把数据传给父组件.在父组件做表单的提交. github内已经提到过这个问题(https://gith ...

  8. swoole 创建web服务器

    http_server.php $http = new swoole_http_server("0.0.0.0", 9501); // 请求监听事件 $http->on('r ...

  9. react-native-mapbox-gl

    mapbox是基于谷歌地图集成的地图插件,可以在很多平台使用,具体可以看mapbox官网.这里具体讲解“react-native-mapbox-gl”插件,是mapbox结合react native封 ...

  10. 微软牛津计划——声纹识别与视频识别API上线啦!

    上个月,我们发布了牛津计划机器学习的情感识别API,能够帮助不同平台的开发者轻松添加智能应用,而无需精通人工智能领域.牛津计划仅仅是微软在人工智能领域探索中的一个实例,而我们的期望是实现更加注重个人使 ...