Spring+SpringMVC需要的jar包:
commons-logging.jar;jstl.jar; standard-1.1.2.jar; com.springsource.org.apache.commons.fileupload-1.2.3.jar;
com.springsource.org.apache.commons.io-1.4.0.jar;spring-aop.3.2.0.RELEASE.jar; spring-aspects.3.2.0.RELEASE.jar;
spring-beans.3.2.0.RELEASE.jar; spring-context.3.2.0.RELEASE.jar; spring-context-support.3.2.0.RELEASE.jar;spring-core.3.2.0.RELEASE.jar;
spring-expression.3.2.0.RELEASE.jar; spring-instrument.3.2.0.RELEASE.jar; spring-instrument-tomcat.3.2.0.RELEASE.jar;
spring-jms.3.2.0.RELEASE.jar;spring-orm.3.2.0.RELEASE.jar; spring-oxm.3.2.0.RELEASE.jar;spring-struts.3.2.0.RELEASE.jar;
spring-test.3.2.0.RELEASE.jar;spring-tx.3.2.0.RELEASE.jar; spring-web.3.2.0.RELEASE.jar;
Hibernate4的jar包:
antlr-2.7.7.jar;dom4j-1.6.1.jar; hibernate-commons-annotations-4.0.4.Final.jar;hibernate-core-4.1.6.Final.jar;
hibernate-jpa-2.1-api-1.0.0.Final.jar;jandex-1.1.0.Final.jar; javassist-3.18.1-GA.jar;jboss-logging-3.1.3.GA.jar;
jboss-logging-annotations-1.2.0.Beta1.jar;jboss-transaction-api_1.2_spec-1.0.0.Final.jar
其他Jar:
aopalliance.jar; mysql-connector-java-5.1.19-bin.jar;
目录结构图:
Controller(控制层)、Dao(持久层)、Service(业务逻辑层)三层架构;User实体类;hibernate.cfg.xml用于配置个人的实体类映射关系;applicationContext_edifier.xml用于配置个人的bean;applicationContext-hibernate.xml中配置数据源,SessionFactory,事务以及hibernate中的一些配置选项(由于这里配置了,所以hibernate配置文件中就不需要陪了);spring-servletAnnatation.xml用来配置springMVC的。
在配置hibernate时,有两种方法类配置:
一种是通过hibernate自己配置数据源及其自身的一些配置。
另一种是通过Spring来配置hibernate的一些属性。
我们下面用的就是第二种使用Spring来配置hibernate。
先来看web.xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>SpringMVC10</display-name>
<description>This a description of my SpringMVC10 app made by Eclipse</description>
<context-param> <!-- 要修改listener的路径需要在context-param中配置如下 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:config/applicationContext-hibernate.xml</param-value>
</context-param>
<filter><!-- 这个filter是Spring自带字符编码过滤器 -->
<filter-name>encodingFilter</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:config/spring-servletAnnotation.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.jsp</welcome-file>
</welcome-file-list>
</web-app>
接下来是Spring的配置文件applicationContext-hibernate.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: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">
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/spring_hibernate"></property>
<property name="username" value="root"></property>
<property name="password" value="edifier"></property>
</bean>
<!-- 配置SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property><!-- 使用上面的数据源 -->
<property name="hibernateProperties"><!-- 配置hibernate的属性 -->
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="default_schema">springMVCHibernate</prop>
</props>
</property>
<property name="configLocations">
<list>
<value><!-- 配置个人的hibernate配置文件 -->
classpath*:com/edifier/springmvc/hibernate/hibernate.cfg.xml
</value>
</list>
</property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 设置传播方式,是否懒加载,是否为抽象类 -->
<bean id="transactionBase" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" lazy-init="true" abstract="true">
<property name="transactionManager" ref="transactionManager"></property>
<property name="transactionAttributes">
<props>
<prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="get*">PROPAGATION_NEVER</prop>
</props>
</property>
</bean>
<!-- 引入个人Spring bean配置文件 -->
<import resource="../com/edifier/springmvc/spring/applicationContext_edifier.xml"/>
</beans>
然后是SpringMVC配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- 注解扫描包 -->
<context:component-scan base-package="com.edifier.springmvc.controller"></context:component-scan>
<!-- 开启注解 -->
<mvc:annotation-driven/>
<!-- 静态资源访问过滤静态文件,location告诉服务器,访问/img/目录的时候直接按照/img/...的格式访问。
因为在web.xml中写的是<url-pattern>/</url-pattern>过滤的所有 请求,包括对静态文件的如jmg,js,css等的请求,
所以这里需要配一个过滤器进行再次过滤-->
<mvc:resources location="/img/" mapping="/img/**"/>
<mvc:resources location="/js/" mapping="/js/**"/>
<mvc:resources location="/css/" mapping="/css/**"/>
<!-- 【配置视图解析器】 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property><!-- 视图的前缀,相当于配置视图的目录 -->
<property name="suffix" value=".jsp"></property><!-- 视图的后缀,相当于配置视图的格式如:".jsp" -->
</bean>
</beans>
接下类是个人的hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class="com.edifier.springmvc.entity.User"/>
</session-factory>
</hibernate-configuration>
个人的applicationContext_edifier.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.xsd">
<!-- 为持久类加载sessionFactory -->
<bean id="userDao" class="com.edifier.springmvc.dao.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 配置一个基础业务bean -->
<bean id="userServiceBase" class="com.edifier.springmvc.service.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<!-- 事务一般放在业务逻辑层而不是dao层,基础业务bean本身不配置事务,而是另外再配置一个业务bean继承基础事务bean-->
<bean id="userService" parent="transactionBase">
<!-- 返回一个基础了事务的基础业务bean,这个类继承让这个类基础基础事务bean-->
<property name="target" ref="userServiceBase"></property>
</bean>
</beans>
Controller类:
package com.edifier.springmvc.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.edifier.springmvc.entity.User;
import com.edifier.springmvc.service.UserService;
@Controller
@RequestMapping("/user")
public class UserController {
@Resource(name="userService")
private UserService userService;
@RequestMapping("/toAddUser")
public String toAddUser(){
return "/addUser";//这里返回的是addUser.jsp视图
}
@RequestMapping("/addUser")
public String addUser(User user){
userService.addUser(user);
System.out.println(user.toString());
return "redirect:/user/getAllUser";//重定向到/user/getAllUser
}
@RequestMapping("/getAllUser")
public String getAllUser(HttpServletRequest request){
List<User> userList = userService.getAllUser();
request.setAttribute("userList", userList);
return "/userManager";
}
@RequestMapping("/deleteUser")//使用Ajax,故返回值为void
public void deleteUser(String id,HttpServletResponse response){
int uid = Integer.parseInt(id);
String result = "{\"userName\":\"error\"}";
if(userService.deleteUser(uid)){
result = "{\"userName\":\"success\"}";
}
PrintWriter pw = null;
response.setContentType("application/json");
try{
pw = response.getWriter();
pw.write(result);
} catch (IOException e){
e.printStackTrace();
}
}
@RequestMapping("/getUser")
public String getUser(int id, HttpServletRequest request){
User user = userService.getUser(id);
request.setAttribute("user", user);
return "/editUser";
}
@RequestMapping("/updateUser")
public String updateUser(User user, HttpServletRequest request){
userService.updateUser(user);
return "redirect:/user/getAllUser";
}
}
业务层UserServiceImpl:
package com.edifier.springmvc.service;
import java.util.List;
import com.edifier.springmvc.dao.UserDao;
import com.edifier.springmvc.entity.User;
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void addUser(User user) {
userDao.addUser(user);
}
@Override
public boolean deleteUser(int id) {
return userDao.deleteUser(id);
}
@Override
public boolean updateUser(User user) {
return userDao.updateUser(user);
}
@Override
public List<User> getAllUser() {
return userDao.getAllUser();
}
@Override
public User getUser(int id) {
return userDao.getUser(id);
}
}
持久层UserDaoImpl:
package com.edifier.springmvc.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import com.edifier.springmvc.entity.User;
public class UserDaoImpl implements UserDao {
//在Hibernate3时这里用的是HibernateDaoSupport这个类来获取sessionFactory</span>
//在Hibernate4中HibernateDaoSupport被去掉了,这里直接用set/get方法注入sessionFactory即可</span>
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public void addUser(User user) {
sessionFactory.getCurrentSession().save(user);
}
@Override
public boolean deleteUser(int id) {
String hql = "delete User u where u.id=?";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setInteger(0, id);
int line = query.executeUpdate();
boolean result = line>0;
return result;
}
@Override
public boolean updateUser(User user) {
String hql = "update User u set u.userName=?, u.age=?, u.sex=? where u.id=?";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString(0, user.getUserName());
query.setString(1, user.getAge());
query.setString(2, user.getSex());
query.setInteger(3, user.getId());
int line = query.executeUpdate();
boolean result = line>0;
return result;
}
@Override
public List<User> getAllUser() {
String hql = "from User";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
return query.list();
}
@Override
public User getUser(int id) {
String hql = "from User u where u.id=?";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setInteger(0, id);
User user = (User) query.uniqueResult();
return user;
}
}
实体类User:
package com.edifier.springmvc.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="t_user")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@Column(name="userName", length=30, nullable=false, unique=true)
private String userName;
@Column(name="age", length=30, nullable=false)
private String age;
@Column(name="sex", length=30, nullable=false)
private String sex;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "User [id=" + id + ", userName=" + userName + ", age=" + age
+ ", sex=" + sex + "]";
}
}
页面代码
addUser.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page isELIgnored="false"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>add User page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript">
function addUser(){
var myaction = document.forms[0];
myaction.action="../user/addUser";
myaction.method="post";
myaction.submit();
}
</script>
</head>
<body>
<h1>添加用户</h1>
<br/>
<form>
姓名:<input type="text" name="userName"/><br/>
年龄:<input type="text" name="age"/><br/>
性别:<input type="text" name="sex"/><br/>
<input type="button" value="添加" οnclick="addUser()">
</form>
</body>
</html>
userManager.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page isELIgnored="false"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>User Manager page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript" src="../js/jquery_1.8.1.js"></script>
<script type="text/javascript">
function deleteUser(id){
$.get("../user/deleteUser?id="+id,function(data){
if("success" == data.userName){
alert("删除成功");
window.location.reload();
}else{
alert("删除失败");
}
});
}
</script>
</head>
<body>
<h1>用户管理</h1>
<br/>
<table>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>编辑</th>
</tr>
<c:if test="${! empty userList}">
<c:forEach var="user" items="${userList}">
<tr>
<td><c:out value="${user.userName}"></c:out></td>
<td><c:out value="${user.age}"></c:out></td>
<td><c:out value="${user.sex}"></c:out></td>
<td>
<button οnclick="deleteUser(${user.id})">删除</button>
<a href="../user/getUser?id=${user.id}">修改</a>
</td>
</tr>
</c:forEach>
</c:if>
</table>
</body>
</html>
editUser.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page isELIgnored="false"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Edit User page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript">
function editUser(){
var myaction = document.forms[0];
myaction.action="../user/updateUser";
myaction.method="post";
myaction.submit();
}
</script>
</head>
<body>
<h1>用户管理</h1>
<br/>
<form action="">
<input type="hidden" name="id" value="${user.id}">
<table>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
</tr>
<tr>
<td><input type="text" name="userName" value="${user.userName}"></td>
<td><input type="text" name="age" value="${user.age}"></td>
<td><input type="text" name="sex" value="${user.sex}"></td>
</tr>
</table>
<input type="button" value="修改" οnclick="editUser()">
</form>
</body>
</html>
index.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<a href="user/toAddUser">添加用户</a>
<a href="user/getAllUser">查看用户</a>
</body>
</html>