您的位置:首页 > 编程语言 > Java开发

Struts2-Spring2.5_Hibernate3.2整合示例(简单注册)

2011-03-07 16:02 162 查看

用Struts2-Spring2.5_Hibernate3.2实现一个非常非常简单的登录注册示例,附件中有项目的源码。加入相应的包后,就可以直接使用

项目的结构如下:

如附件中图片所示。

下面就一步一步进行说明

1)首先需要将Struts2、Spring2.5、Hibernate3.2所需要的jar包全部导入到项目中(本例中Hibernate3.2用的是MyEclipse自带的jar包,如何导入请查看其他博文,相关文章都有介绍)

2)配置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">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 配置spring的监听器 -->
<!--
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>
如果Spring配置文件在/WEB-INF下,则用上面的内容进行配置,如果Spring配置文件直接放在工程src下,则用下面的
内容进行配置
-->
<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>
<!-- 配置OpenSessionInViewFilter,必须在struts2监听之前 -->
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<!-- 设置监听加载上下文 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

 

3)编写model类---User

package com.chenfei.model;

public class User {
private Long id;
private String username;
private String password;
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;
}
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
}

 

 

4)编写Struts Action

      

package com.chenfei.action;

import com.chenfei.model.User;
import com.chenfei.service.LoginManager;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

private User user;
private LoginManager loginManager;

@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
if(loginManager.isLogin(user.getUsername(),user.getPassword()))
return "success";
else
return "error";
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public LoginManager getLoginManager() {
return loginManager;
}
public void setLoginManager(LoginManager loginManager) {
this.loginManager = loginManager;
}
}

 

5)编写业务处理层(尽量是面向接口的编程)

  

package com.chenfei.service;

public interface LoginManager {
public boolean isLogin(String username,String password);

}

 

上面是接口,下面是他的实现

   

package com.chenfei.service;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.chenfei.dao.UserDao;
import com.chenfei.model.User;

public class LoginManagerImpl implements LoginManager {
private User user;//需要注入一个
private UserDao userDao;
public boolean isLogin(String username, String password) {
// TODO Auto-generated method stub

if(username!=null&&password!=null&&!username.equals("")&&!password.equals(""))
{
user.setUsername(username);
user.setPassword(password);
userDao.addUser(user);
return true;
}
else
{
System.out.println("~~~~~~~~~~~~~~~~~~Wrong~~~~~~~~~~~~~~~~~");
return false;
}
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public UserDao getUserDao() {
return userDao;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}

}

 

 

6)编写Dao(尽量是面向接口的编程)

package com.chenfei.dao;

import com.chenfei.model.User;

public interface UserDao {
public void addUser(User user);

}

 

 

上面是接口,下面是他的实现

package com.chenfei.dao;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.chenfei.model.User;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
//继承自HibernateDaoSupport
public void addUser(User user) {
// TODO Auto-generated method stub
this.getHibernateTemplate().save(user);

}

}

 

7)为了测试AOP,编写一个简单的切面

package com.chenfei.aspect;

public class CheckUser {
public void beforeLogin()
{
System.out.println("登录前的状态");
}
public void afterLogin()
{
System.out.println("登录后的状态");
}

}

 

 

 8)配置Struts的配置文件

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">

<struts>
<package name="default" extends="struts-default" >
<action name="login" class="loginAction">
<result>/welcome.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>

 

 

9)编写Spring的配置文件applicationContext-bean.xml

<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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/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="user" class="com.chenfei.model.User">
</bean>

<bean id="loginAction" class="com.chenfei.action.LoginAction"
scope="prototype">
<property name="loginManager" ref="loginManager"></property>
<property name="user" ref="user">
</property>
</bean>

<bean id="loginManager" class="com.chenfei.service.LoginManagerImpl">
<property name="user" ref="user"></property>
<property name="userDao" ref="userDao"></property>
</bean>

<bean id="userDao" class="com.chenfei.dao.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>

<!-- 显示AOP的用法 -->
<bean id="checkUser" class="com.chenfei.aspect.CheckUser"></bean>
<aop:config>
<aop:aspect ref="checkUser">
<aop:pointcut id="check" expression="execution(* *.isLogin(..))"/>
<aop:before method="beforeLogin"  pointcut-ref="check"/>
<aop:after method="afterLogin"  pointcut-ref="check"/>
</aop:aspect>
</aop:config>

<!-- 配置sessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
</bean>

<!-- 事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>

<!-- 配置事务传播特性,本例仅以配置add开始的方法,事务传播特性为required -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>

<!-- 配置哪些类的方法参与事务,当前com.chenfei.dao包中的子包,
类中所有方法需要,还需要参考tx:advice的设置 -->
<aop:config>
<aop:pointcut id="addManagerMethod" expression="execution(* com.chenfei.dao.*.*(..))"/><!--expression写的时候一定注意,否则会出现问题-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="addManagerMethod"/>
</aop:config>

</beans>

 

10)编写Hibernate配置文件

                                                         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">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

<session-factory>
<property name="connection.username">root</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/user
</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="myeclipse.connection.profile">
MyDriver
</property>
<property name="connection.password">113801</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="current_session_context_class">thread</property>
<mapping resource="./User.hbm.xml" />

</session-factory>

</hibernate-configuration>

 

                                                            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 package="com.chenfei.model">
<class name="User" table="user">
<id name="id" type="long">
<column name="id" />
<generator class="increment"></generator>
</id>
<property name="username" type="string">
<column name="username" length="45" not-null="true" />
</property>
<property name="password" type="string">
<column name="password" length="45" not-null="true" />
</property>
</class>
</hibernate-mapping>

  

11)相关页面

                                                                login.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>登陆</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>
<form action="login" method="post">
<s:textfield name="user.username" label="用户名"></s:textfield>
<s:password name="user.password" label="密码"></s:password>
<s:submit value="submit" align="left"></s:submit>
</form>
</body>
</html>

 

                                                                  error.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>欢迎您的光临</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>
登录错误,请检查您的用户名跟密码,<a href="login.jsp">重新登录。</a>
</body>
</html>

 

                                                                   welcome.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>欢迎您的光临</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>
欢迎您,<s:property value="user.username"/>
<s:debug></s:debug>
</body>
</html>

 

经过以上步骤,就可实现一个非常非常弱智的注册系统~~

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: