struts2.0.14+spring2.5+hibernate3.2整合方法一
spring只写bean,不写注入;action的class写包名加类名
加入所需jar:
antlr-2.7.6 aspectjrt aspectjweaver commons-collections-3.1 commons-dbcp-1.2.2 commons-logging-1.0.4 commons-pool-1.3 dom4j-1.6.1 ejb3-persistence freemarker-2.3.8 hibernate3 hibernate-annotations hibernate-commons-annotations javassist-3.4.GA jta-1.1 log4j-1.2.15 mysql-connector-java-5.0.4-bin ognl-2.6.11 slf4j-api-1.5.2 slf4j-log4j12-1.5.2 spring struts2-core-2.0.14 struts2-spring-plugin-2.0.14 xwork-2.0.7
applicationContext-common.xml
<?xml version="1.0" encoding="GBK"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!-- 使Spring关注Annotation -->
<context:annotation-config />
<!-- 让Spring通过自动扫描来查询和管理Bean -->
<context:component-scan base-package="com.*.domain" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<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>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>demo/domain/Person.hbm.xml</value>
</list>
</property>
<!-- annotatedScanPackages可以自动搜索某个package的全部标记@Entity class -->
<property name="packagesToScan" value="demo.domain" />
</bean>
<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/test"></property>
<property name="username" value="root"></property>
<property name="password" value="system"></property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<!-- 配置事务的传播特性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="modify*" propagation="REQUIRED" />
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 哪些类的哪些方法参与事务 -->
<aop:config>
<aop:pointcut id="allManagerMethod" expression="execution(* demo.service.*.*(..))" />
<aop:advisor pointcut-ref="allManagerMethod" advice-ref="txAdvice" />
</aop:config>
</beans>
applicationContext-beans.xml
<?xml version="1.0" encoding="GBK"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="userService" class="demo.service.UserServiceImpl"></bean>
<bean id="userDao" class="demo.dao.UserDaoImpl"></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.0.dtd">
<struts>
<!-- 已经导入了struts-spring-plugin包所以在struts.xml里面不需要再配置这个常量
<constant name="struts.objectFactory" value="org.apache.struts2.spring.StrutsSpringObjectFactory" />-->
<package name="struts2" extends="struts-default">
<action name="Login" class="demo.action.LoginAction" method="Login">
<result name="success" type="redirect">listUser.action</result>
<result name="input">/login.jsp</result>
</action>
<action name="addUser" class="demo.action.LoginAction" method="addUser">
<result name="success">/addUser.jsp</result>
</action>
<action name="saveUser" class="demo.action.LoginAction" method="saveUser">
<result name="success" type="redirect">listUser.action</result>
</action>
<action name="listUser" class="demo.action.LoginAction" method="listUser">
<result name="success" >/listUser.jsp</result>
</action>
<action name="securityCodeImage" class="demo.action.LoginAction" method="securityCodeImage">
<result name="success" >/listUser.jsp</result>
</action>
</package>
</struts>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>flushMode</param-name>
<param-value>AUTO</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</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>GBK</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Person.java
package demo.domain;
public class Person {
private int id;
private String nameString;
private String sex;
private String address;
private String duty;
private String phone;
private String description;
}
Person.hbm.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class table="t_person" name="demo.domain.Person">
<id access="field" name="id">
<generator class="native"/>
</id>
<property name="nameString" access="field"/>
<property name="sex" access="field"/>
<property name="address" access="field"/>
<property name="duty" access="field"/>
<property name="phone" access="field"/>
<property name="description" access="field"/>
</class>
</hibernate-mapping>
User.java
package demo.domain;
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;
@Entity @Table(name="t_user")
public class User {
@Id
@GenericGenerator(name="Ngenerator",strategy="native")
@GeneratedValue(generator="Ngenerator")
@Column(name = "id", unique = true, nullable = false)
private String resourceId;
@Column(name = "account", length = 500)
private String account;
@Column(name = "userName", length = 500)
private String userName;
@Column(name = "password", length = 500)
private String passWord;
public String getResourceId() {
return resourceId;
}
public void setResourceId(String resourceId) {
this.resourceId = resourceId;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
}
LoginAction.java
package demo.action;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
import demo.domain.User;
import demo.service.UserService;
public class LoginAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private UserService userService;
private User user=new User();
private List<User> listUser;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String Login() throws Exception {
if(userService.isLogin(user.getUserName(), user.getPassWord())){
return SUCCESS;
}
return INPUT;
}
public String listUser() throws Exception {
listUser=userService.findUserList();
System.out.print(listUser.size());
return SUCCESS;
}
public String addUser() throws Exception {
return SUCCESS;
}
public String saveUser() throws Exception {
userService.save(user);
return SUCCESS;
}
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
public List<User> getListUser() {
return listUser;
}
public void setListUser(List<User> listUser) {
this.listUser = listUser;
}
}
UserDaoImpl.java
package demo.dao;
import java.util.List;
import demo.domain.User;
import demo.utils.MyHibernateDaoSupport;
public class UserDaoImpl extends MyHibernateDaoSupport implements UserDao {
public void save(User user){
super.getHibernateTemplate().save(user);
}
public void delete(int id){
super.getHibernateTemplate().delete(super.getHibernateTemplate().load(User.class, id));
}
public void update(User user){
super.getHibernateTemplate().update(user);
}
@SuppressWarnings("unchecked")
public List<User> query(){
return super.getHibernateTemplate().find("from User");
}
public User get(int id){
return (User)super.getHibernateTemplate().get("from User", id);
}
@Override
public List<User> findUserList() {
return super.getHibernateTemplate().find("from User");
}
@Override
public boolean isLogin(String userName, String passWord) {
List<User> l= getHibernateTemplate().find("from User where userName=? and passWord=?",new String[]{userName, passWord});
if(l.size()>0){
return true;
}
return false;
}
}
UserServiceImpl.java
package demo.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import demo.dao.UserDao;
import demo.domain.User;
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
public void save(User user){
userDao.save(user);
}
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public List<User> findUserList() {
List<User> lu=userDao.findUserList();
return lu;
}
@Override
public boolean isLogin(String userName, String passWord) {
return userDao.isLogin( userName, passWord);
}
}
MyHibernateDaoSupport.java
package demo.utils;
import javax.annotation.Resource;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class MyHibernateDaoSupport extends HibernateDaoSupport {
@Resource(name="sessionFactory") //为父类HibernateDaoSupport注入sessionFactory的值
public void setSuperSessionFactory(SessionFactory sessionFactory){
super.setSessionFactory(sessionFactory);
}
}
addUser.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!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>
</head>
<body>
<s:form action="saveUser" method="post">
<s:textfield name="user.userName" label="用户名"></s:textfield>
<s:password name="user.passWord" label="密码"></s:password>
<s:submit></s:submit>
</s:form>
</body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%
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">
</head>
<script type="text/javascript">
function gotoLogin(){
window.location.href="<%=basePath%>Login.action";
}
function addUser(){
window.location.href="<%=basePath%>addUser.action";
}
</script>
<body>
<form action="Login.action" method="post">
<a href="#" onclick="gotoLogin()">进入登录页面</a>
<br>
<a href="#" onclick="addUser()">添加用户</a>
</form>
</body>
</html>
listUser.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!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>
</head>
<body>
用户名=密码<br/>
<c:forEach items="${listUser }" var ="user">
${user.userName }=${user.passWord }<br/>
</c:forEach>
</body>
</html>
login.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!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>
</head>
<script type="text/javascript">
window.onload=function(){
var verifyObj = document.getElementById("Verify");
verifyObj.onclick=function(){
this.src="securityCodeImage.action?timestamp="+new Date().getTime();
};
}
</script>
<body>
<s:form action="Login" method="post">
<s:textfield name="user.userName" label="用户名"></s:textfield>
<s:password name="user.passWord" label="密码"></s:password>
<div id="Verify"></div>
<s:submit></s:submit>
</s:form>
</body>
</html>