这是一个springmvc+hibernate框架整合的demo,拿出来分享,希望对初学框架的人有所帮助;
- 开发前的准备工作
1.所需要的jar包,主要有springmvc jar包,hibernate jar包 ,数据库连接驱动包,数据源jar包,等 ;
具体如下:
- 建立Java web项目
目录结构具体如下:
- 核心配置文件介绍
1.项目核心入口配置文件(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_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>springMVC</display-name>
<!-- Spring应用上下文配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/applicationContext-*.xml</param-value>
</context-param>
<!-- Spring应用上下文监听器 -->
<!-- ContextLoaderListener监听器的作用就是启动Web容器时,自动装配ApplicationContext的配置信息。 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置spring核心servlet -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<!-- 可以自定义servlet.xml配置文件的位置和名称,默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如spring-servlet.xml -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- url-pattern配置为/,不带文件后缀,会造成其它静态文件(js,css等)不能访问。如配为*.do,则不影响静态文件的访问 -->
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 静态资源加载 -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<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>
<!-- 配置Session -->
<filter>
<filter-name>openSession</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<!-- 请注意,此处必须定义,否则后面会报错,具体是什么,笔者没截图,记不太清楚了 -->
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>openSession</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 项目文件编码设置 -->
<filter>
<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-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-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>
2.springmvc配置文件(spring-servlet.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"
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-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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- 开启注解 -->
<mvc:annotation-driven />
<!-- 加载controller组件的位置 -->
<context:component-scan base-package="com.liu.controller" />
<!-- 加载静态资源 -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:resources mapping="/images/**" location="/images/" />
<mvc:resources mapping="/js/**" location="/js/" />
<!-- 视图解析 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/resources/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
3.spring上下文核心配置文件(applicationContext-core.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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- oracle配置数据源 -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"></property>
<property name="username" value="username"></property>
<property name="password" value="123456"></property>
</bean>
<!-- MySQL配置数据源 -->
<!-- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value=""></property>
</bean> -->
<!-- 配置SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<!-- <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> -->
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="connection.autocommit">true</prop>
</props>
</property>
<!-- 注解扫描的包 -->
<property name="annotatedClasses">
<list>
<value>com.liu.entity.User</value>
</list>
</property>
</bean>
<!-- 配置一个事务管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 配置事务,使用代理的方式 -->
<bean id="transactionProxy"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
abstract="true">
<property name="transactionManager" ref="transactionManager"></property>
<property name="transactionAttributes">
<props>
<prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="modify*">PROPAGATION_REQUIRED,-myException</prop>
<prop key="del*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
</beans>
- 业务逻辑bean层注册,及spring bean代理文件(applicationContext-beans.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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--dao层 bean -->
<bean id="UserDaoImplTarget" class="com.liu.daoImpl.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!--service层 bean -->
<bean id="UserService" class="com.liu.service.UserService">
<property name="UserDaoImpl" ref="UserDaoImplTarget"></property>
</bean>
<!-- 此处为spring 代理 dao层bean-->
<bean name="UserDaoImpl" parent="transactionProxy">
<property name="target" ref="UserDaoImplTarget"></property>
</bean>
</beans>
- 此实体的定义应用了springmvc的注解,省去了传统的Hibernate跟数据库之间的映射配置文件(User.java)
package com.liu.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
/**
* 此实体的定义应用了springmvc的注解,省去了传统的Hibernate跟数据库之间的映射配置文件
* @author will
*
*/
@Entity
@Table(name="T_USER")
public class User {
@Id
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name = "system-uuid",strategy="uuid")
@Column(length=100)
private String id;
@Column(length=32)
private String userName;
@Column(length=32)
private String age;
public String getId() {
return id;
}
public void setId(String 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;
}
}
- 业务逻辑层介绍
1.业务dao层(UserDao.java):
package com.liu.dao;
import java.util.List;
import com.liu.entity.User;
public interface UserDao {
public User getUser(String id);
public List<User> getAllUser();
public void addUser(User user);
public boolean delUser(String id);
public boolean updateUser(User user);
}
2.业务dao层实现(UserDaoImpl.java):
package com.liu.daoImpl;
import java.util.List;
import com.liu.dao.UserDao;
import com.liu.entity.User;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
public class UserDaoImpl implements UserDao{
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
/**
* 根据用户id查询用户
*/
@Override
public User getUser(String id) {
String hql = "from User u where u.id=?";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString(0, id);
return (User)query.uniqueResult();
}
/**
* 查询所有用户
*/
@Override
public List<User> getAllUser() {
/* String hql = "select * from t_user";
System.out.print("--------------------->");*/
Criteria crit = sessionFactory.getCurrentSession().createCriteria(User.class);
System.out.print(crit.list().size()+"--------------------->");
return crit.list();
}
/**
* 添加用户
*/
@Override
public void addUser(User user) {
System.out.println("用户名:==impl===="+user.getUserName());
System.out.println("用户名:==impl===="+user.getAge());
Transaction tx = sessionFactory.getCurrentSession().beginTransaction();
sessionFactory.getCurrentSession().save(user);
tx.commit();
sessionFactory.getCurrentSession().flush();
System.out.println("用户名:==add====");
}
/**
* 根据用户id删除用户
*/
@Override
public boolean delUser(String id) {
String hql = "delete User u where u.id = ?";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString(0, id);
return (query.executeUpdate() > 0);
}
/**
* 编辑用户
*/
@Override
public boolean updateUser(User user) {
String hql = "update User u set u.userName = ?,u.age=? where u.id = ?";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString(0, user.getUserName());
query.setString(1, user.getAge());
query.setString(2, user.getId());
return (query.executeUpdate() > 0);
}
}
- 业务service层实现(UserService.java)
package com.liu.service;
import java.util.List;
import com.liu.dao.UserDao;
import com.liu.daoImpl.UserDaoImpl;
import com.liu.entity.User;
public class UserService implements UserDao{
private UserDaoImpl userDaoImpl;
public UserDaoImpl getUserDaoImpl() {
return userDaoImpl;
}
public void setUserDaoImpl(UserDaoImpl userDaoImpl) {
this.userDaoImpl = userDaoImpl;
}
@Override
public User getUser(String id) {
return userDaoImpl.getUser(id);
}
@Override
public List<User> getAllUser() {
return userDaoImpl.getAllUser();
}
@Override
public void addUser(User user) {
userDaoImpl.addUser(user);
}
@Override
public boolean delUser(String id) {
return userDaoImpl.delUser(id);
}
@Override
public boolean updateUser(User user) {
return userDaoImpl.updateUser(user);
}
}
- 主要页面介绍
1.首页(Login.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">
<title>首页</title>
</head>
<body>
<h5><a href="/springmvc/user/getAllUser">进入用户管理页</a></h5>
</body>
</html>
2.结果显示处理页面(Index.jsp);
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%
String path = request.getContextPath();
%>
<script type="text/javascript" src="<%=path%>/js/jquery-1.7.2.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function del(id){
$.get("/springmvc/user/delUser?id="+id,function(data){
if("success" == data.result){
alert("删除成功");
window.location.reload();
}else{
alert("删除失败");
}
});
}
</script>
</head>
<body>
<h6><a href="/springmvc/user/toAddUser">添加用户</a></h6>
<table border="1">
<tbody>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
<c:if test="${!empty userList }">
<c:forEach items="${userList }" var="user">
<tr>
<td>${user.userName}</td>
<td>${user.age }</td>
<td>
<a href="/springmvc/user/getUser?id=${user.id }">编辑</a>
<a href="javascript:del('${user.id }')">删除</a>
</td>
</tr>
</c:forEach>
</c:if>
</tbody>
</table>
</body>
</html>
3.添加页面(addUser.jsp);
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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">
<title>Insert title here</title>
<script type="text/javascript">
function addUser(){
var form = document.forms[0];
form.action = "/springmvc/user/addUser";
form.method="post";
form.submit();
}
</script>
</head>
<body>
<h1>添加用户</h1>
<form action="" name="userForm">
姓名:<input type="text" name="userName">
年龄:<input type="text" name="age">
<input type="button" value="添加" onclick="addUser()">
</form>
</body>
</html>
- 更新页面(editUser.jsp);
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%
String path = request.getContextPath();
%>
<script type="text/javascript" src="<%=path %>/js/jquery-1.9.1.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>编辑用户</h1>
<form action="/springmvc/user/updateUser" name="userForm" method="post">
<input type="hidden" name="id" value="${user.id }">
姓名:<input type="text" name="userName" value="${user.userName }">
年龄:<input type="text" name="age" value="${user.age }">
<input type="submit" value="编辑" >
</form>
</body>
</html>