操作流程:
工程结构:
在web.xml文件中配置Spring MVC
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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>SpringTest</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/applicationContext.xml</param-value> </context-param> <servlet> <servlet-name>springTest</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springTest</servlet-name> <!-- 支持REST风格的URL,springTest捕获所有的请求 --> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
springTest-servlet.xml
<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:context="http://www.springframework.org/schema/context" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 自动扫描com.wgc.web 包下的@Controller标注的类控制器类 --> <context:component-scan base-package="com.wgc.web" /> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <mvc:annotation-driven/> <!-- 处理静态资源 --> <mvc:resources mapping="/static/**" location="/WEB-INF/static/" /> <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver" p:order="0" p:defaultContentType="text/html" p:ignoreAcceptHeader="true" p:favorPathExtension="false" p:favorParameter="true" p:parameterName="content"> <property name="mediaTypes"> <map> <entry key="html" value="text/html" /> <entry key="xml" value="application/xml" /> <entry key="json" value="application/json" /> </map> </property> <property name="defaultViews"> <list> <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" p:renderedAttributes="users" /> </list> </property> </bean> <!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:order="10" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> </bean> </beans>
applicationContext.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" 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 "> <!-- 数据访问层配置 --> <import resource="classpath:/springTest-dao.xml" /> <!--服务层配置 --> <import resource="classpath:/springTest-service.xml" /> </beans>
springTest-dao.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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" 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/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <!-- 扫描com.wgc.dao包下所有标注@Repository的DAO组件 --> <context:component-scan base-package="com.wgc.dao"/> <!-- 配置数据源 --> <context:property-placeholder location="classpath:jdbc.properties"/> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" /> <!-- 使用Spring JDBC:声明JdbcTemplateBean --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan"> <list> <value>com.wgc.domain</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.cache.provider_class"> org.hibernate.cache.EhCacheProvider </prop> <prop key="hibernate.cache.use_query_cache">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> </bean> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate" p:sessionFactory-ref="sessionFactory" /> </beans>
springTest-service.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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/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"> <context:component-scan base-package="com.wgc.service"/> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory" /> </beans>
User.java
package com.wgc.domain;
public class User {
private String userid;
private String username;
private String pass;
public User() {}
public User(String username, String pass) {
this.username = username;
this.pass = pass;
}
public String getUserid() {
return userid;
}
public String getUsername() {
return username;
}
public String getPass() {
return pass;
}
public void setUserid(String userid) {
this.userid = userid;
}
public void setUsername(String username) {
this.username = username;
}
public void setPass(String pass) {
this.pass = pass;
}
}
Controller_01.java
package com.wgc.web;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.wgc.domain.User;
@Controller
@RequestMapping("/test")
public class Controller_01 {
@RequestMapping("/JSON")
public String testJSON() {
System.out.println("testJSON");
return "testJSON";
}
@RequestMapping("/getJSON")
public ModelAndView getJSON() {
System.out.println("getJSON");
ModelAndView mav = new ModelAndView();
List<User> users = this.getUsers();
mav.addObject("users", users);
mav.setViewName("testJSON");
return mav;
}
private List<User> getUsers() {
List<User> users = new ArrayList<User>();
users.add(new User("user_01", "123"));
users.add(new User("user_02", "456"));
return users;
}
}
testJSON.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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="../static/js/jquery-1.10.1.js"></script>
<script type="text/javascript">
$(function(){
$("#testJson").click(function(){
$.ajax({
type:"GET",
url:"http://localhost:8080/SpringTest/test/getJSON?content=json",
dataType:"json",
contentType:'application/json;charset=UTF-8',
success:function(data){
$("#result").empty();
var strResult = "";
var users = data.users;
for(index in users){
strResult += "<div class='comment'>用户名:" + users[index].username + "<br />密码:" + users[index].pass + "<hr /></div>";
}
$("#result").html(strResult);
},
error:function(){
alert("error.");
}
});
});
})
</script>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<title>TestJSON</title>
</head>
<body>
<!--
<c:forEach var="user" items="${users}">
<div>
用户名:${user.username}<br/>
密码:${user.pass}<hr/>
</div>
</c:forEach>
-->
<input type="button" id="testJson" value="测试返回JSON类型数据">
<div id="result">获得的数据将会在这里显示</div>
</body>
</html>