原文地址: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. Vue-[v-model]理解示例

    对应文档节点: https://vuefe.cn/v2/guide/components.html#Customizing-Component-v-model <body> <div ...

  2. springboot+mybatis实现动态切换数据源

    前几天有个需求,需要使用不同的数据源,例如某业务要用A数据源,另一个业务要用B数据源.我上网收集了一些资料整合了一下,虽然最后这个需求不了了之了,但是多数据源动态切换还是蛮好用的,所以记录一下,或许以 ...

  3. Django之路由、模板和模型系统 (转载)

    一.路由系统 浏览器会自动给url后加一个“/” django会自动给路由的正则表达式前面加一个“/” django会给任何不带“/”结尾的url语句添加“/”(可设置) 短路路由规则:匹配到第一条就 ...

  4. Spring课程 Spring入门篇 6-2 ProxyFactoryBean及相关内容(上)

    1 解析 1.1 类的方式实现各种通知需要实现的接口 1.2 创建Spring aop代理的优点及方法 1.3 代理控制切入点和通知的顺序的代码实现(具体完全实现,见代码2.1) 1.4 代理方式选择 ...

  5. Maven+MyBatis 初试

    工作中一直使用的都是Hibernate,总是听见有人拿Mybatis和Hibernate做比较,今天尝试来看看. 一.用Maven建立web项目 此处参见 http://www.cnblogs.com ...

  6. svn怎么下载代码到本地

    1. 在我们安装好svn时,在指定的目录中点击鼠标右键SVN Checkout,弹出以下窗口.(在文件夹下各自建好前后台的文件夹分别check) 2. 在URL of repository:(存储库的 ...

  7. jquery获取下拉框中的循环值

    <select class="test" id="projectno" name="projectno"> <option ...

  8. css移动端:acitve效果的实现

    做移动前端也有一些日子了,一直有个问题没有解决,就是与pc端那样的一个:hover的效果,:hover是鼠标指针浮动在其上的元素的一个选择器,但因为在移动端是没有鼠标的,代替的是触摸屏,用户也不是有“ ...

  9. after() 和 remove() 实现替换

    <div class="replacedDiv">this is the replaced div</div> <script>         ...

  10. bzoj2119 [ZJOI2010]base基站选址

    传送门 n年前的考试题,今天才填上…… 听说你们会决策单调性+主席树?然而我多年不写决策单调性,懒得写了……于是就写了一发线段树. 其实线段树应该不难想,毕竟转移是分层转移,并且这个题的转移函数可以快 ...