ssh(struts2+spring3+hibernate3)集成(增删改查)实现
源代码:http://download.csdn.net/detail/tww19920930/5806397
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
This is my JSP page. <br>
<a href="save.jsp">添加用户</a>
<a href="list">查询用户</a>
</body>
</html>
list.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'list.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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<!-- 显示所有的信息 -->
<table border="1">
<tr>
<th>id</th>
<th>username</th>
<th>password</th>
<th>do</th>
</tr>
<s:iterator value="list" id="u">
<tr>
<td>${u.id}</td>
<td>${u.username}</td>
<td>${u.password}</td>
<td><a href="del?user.id=${u.id}">delete</a></td>
</tr>
</s:iterator>
</table>
</body>
</html>
save.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'saveMonkey.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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<!-- 添加一条用户记录到数据库,并且要用list.jsp显示出来 -->
<form action="save" method="post">
username:<input type="text" name="user.username"><br>
password:<input type="password" name="user.password"><br>
<input type="submit" value="save">
</form>
</body>
</html>
error.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'error.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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
error. <br>
</body>
</html>
action/UserAction.java
package action;
import java.util.ArrayList;
import java.util.List;
import service.UserService;
import vo.User;
import com.opensymphony.xwork2.ActionSupport;
public class UserAction extends ActionSupport{
private UserService userService;
private User user;
private List<User> list=new ArrayList<User>();
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<User> getList() {
return list;
}
public void setList(List<User> list) {
this.list = list;
}
public String list() {
list=userService.list();
return SUCCESS;
}
public String save() {
System.out.println(user.getUsername());
int res=userService.save(user);
if (res>0) {
return SUCCESS;
}
return ERROR;
}
public String del() {
// TODO Auto-generated method stub
int res= userService.del(user);
if (res>0) {
return SUCCESS;
}
return ERROR;
}
}
service/UserService.java
package service;
import java.util.List;
import vo.User;
public interface UserService {
public List<User> list();
public int save(User user);
public int del(User user);
}
service.impl.UserServiceImpl.java
package service.impl;
import java.util.List;
import dao.UserDAO;
import service.UserService;
import vo.User;
public class UserServiceImpl implements UserService{
private UserDAO userDAO;
public UserDAO getUserDAO() {
return userDAO;
}
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
public List<User> list() {
return userDAO.list();
}
public int save(User user) {
// TODO Auto-generated method stub
return userDAO.save(user);
}
public int del(User user) {
// TODO Auto-generated method stub
return userDAO.del(user);
}
}
dao.UserDAO.java
package dao;
import java.util.List;
import vo.User;
public interface UserDAO {
public List<User> list();
public int save(User user);
public int del(User user);
}
dao.impl.UserDAOImpl.java
package dao.impl;
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import vo.User;
import dao.UserDAO;
public class UserDAOImpl extends HibernateDaoSupport implements UserDAO{
public List<User> list() {
String hql="from User";
return this.getHibernateTemplate().find(hql);
}
public int save(User user) {
return (Integer) this.getHibernateTemplate().save(user);
}
public int del(User user) {
this.getHibernateTemplate().delete(user);
return 1;
}
}
util
.
HibernateSessionFactory.java
package util;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {
/**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
}
vo.User.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="vo.User" table="user" catalog="shop">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="native" />
</id>
<property name="username" type="java.lang.String">
<column name="username" length="25" />
</property>
<property name="password" type="java.lang.String">
<column name="password" length="25" />
</property>
</class>
</hibernate-mapping>
vo.User.java
package vo;
/**
* User entity. @author MyEclipse Persistence Tools
*/
public class User implements java.io.Serializable {
// Fields
private Integer id;
private String username;
private String password;
// Constructors
/** default constructor */
public User() {
}
/** full constructor */
public User(String username, String password) {
this.username = username;
this.password = password;
}
// Property accessors
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
}
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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<!-- 在url的value中添加数据库连接地址,并且要支持中文 -->
<property name="url"
value="jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf-8">
</property>
<property name="username" value="root"></property>
<property name="password" value="tiger"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="mappingResources">
<list>
<!-- 在value中添加映射文件 -->
<value>vo/User.hbm.xml</value>
</list>
</property>
</bean>
<!-- 添加自定义的bean -->
<bean id="userAction" class="action.UserAction">
<property name="userService" ref="userService"></property>
</bean>
<bean id="userService" class="service.impl.UserServiceImpl">
<property name="userDAO" ref="userDAO"></property>
</bean>
<bean id="userDAO" class="dao.impl.UserDAOImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</beans>
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="default" extends="struts-default" namespace="/">
<!-- 添加action -->
<action name="list" class="userAction" method="list">
<result name="success">/list.jsp</result>
<result name="error">/error.jsp</result>
</action>
<action name="save" class="userAction" method="save">
<result name="success" type="redirectAction">list</result>
<result name="error">/error.jsp</result>
</action>
<action name="del" class="userAction" method="del">
<result name="success" type="redirectAction">list</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>