现在的位置: 首页 > 综合 > 正文

Struts2+Spring2.5+Hibernate3.1实现登陆示例

2012年11月11日 ⁄ 综合 ⁄ 共 12421字 ⁄ 字号 评论关闭

        本人初学struts2,介于此所以对struts2的框架流程不熟悉,这是我的第一个struts2+spring+hibernate的整合程序,一个简单登陆程序,因为本人也是初出茅庐遇到了很多问题,做完之后马上就发布出来希望对那些刚开始学习struts2的同行有所帮助,因为本人也是菜鸟,班门弄斧了就请大家别见笑了。好了不说废话了,我们开始吧!

        首先建立一个web project 工程,我这里的命名是ssh2,先将struts2的包导入到工程下的lib先,这里说明哈struts2的包请到http://struts.apache.org/去下载吧,其中要导入的包有commons-logging-1.0.4.jar、ognl-2.6.11.jar、oro-2.0.8.jar、struts2-core-2.0.12.jar、struts2-spring-plugin-2.0.12.jar、xwork-2.0.6.jar,我这里为了方面我把所有的包都导入进入了,这样方面以后做项目的时候整合完整的包。spring2.5直接在myeclipse下去导入了,由于myeclipse还没有整合struts2到他的插件中去,所以struts2需要手动去导入了.hibernate3.1也是在myeclipse中去导了,导的过程中,会发现有许多包和spring的包有冲突的,这没关系,直接keep存在就行了,然后完整工程包的导入,然后我们开始我们的配置工作.这时候大家可能发现不了包冲突所带来的后果,后面我们发现问题的,这里我就不详细说明包冲突的错误了,我这里提示直接删除asm-2.2.3.jar,因为这个包是hibernate与spring命名冲突的原因所造成的.

  其次,我们开始我们的配置工作了,首先是配置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">

    <!-- 配置spring的监听器 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:org/test/spring/applicationContext*.xml</param-value>
    </context-param>
    <!-- 开启监听 -->
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    <!-- 配置OpenSessionInViewFilter,必须在struts2监听之前 -->
    <filter>
        <filter-name>lazyLoadingFilter</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.FilterDispatcher
        </filter-class>
    </filter>
    <filter-mapping>
    <filter-name>lazyLoadingFilter</filter-name>
    <url-pattern>*.action</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

 

  然后开始配置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: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.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">

 <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"></property>
  <property name="username" value="root"></property>
  <property name="password" value="root"></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>
   </props>
  </property>
  
  <property name="mappingLocations">
   <list>
    <value>classpath:/org/test/vo/*.hbm.xml</value>
   </list>
  </property>
 </bean>
 
 <!--
      | 事务管理
    -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

 <!-- 使用annotation定义事务 -->
 <tx:annotation-driven transaction-manager="transactionManager" /> 
</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"><!-- strust2的版本声明 -->

<struts>
    <constant name="struts.objectFactory" value="spring"/>//这里要特别申明,这是表示struts2的action交有spring来管理
    
    <package name="struts2" extends="struts-default">
        <action name="login" class="org.test.action.LoginAction">
            <result name="success">/result.jsp</result>
            <result name="failer">/failer.jsp</result>
        </action>
    </package>

</struts>

 

  最后,由于spring需要去管理所有的逻辑反转控制,所以需要对dao\service\action这个三个曾进行驻入配置,具体如下:

applicationContext-dao.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: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.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">

       <bean  id="itestdao" class="org.test.dao.TestDAO">
            <property name="sessionFactory">
                <ref bean="sessionFactory"/>
            </property>
       </bean>
</beans>

 

applicationContext-service.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: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.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">

       <bean id="loginService" class="org.test.service.LoginService">
            <property name="itestdao">
                  <ref bean="itestdao"/>
            </property>
       </bean>
</beans>

 

applicationContext-action.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: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.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">

       <bean id="login" class="org.test.action.LoginAction">
            <property name="loginService">
                 <ref bean="loginService"/>
            </property>
       </bean>
</beans>

注意:以上的配置文件其实是struts1+spring=hibernate的配置是大同的,上面的配置文件和applicationContext.xml在同一文件夹下,该工程在org.test.spring,这个路径在web.xml中已经有配置.

 

我把所有的代码都贴上来吧。

所用的数据库表如下:

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
  `userid` int(11) NOT NULL auto_increment,
  `username` varchar(20) NOT NULL,
  `password` varchar(16) NOT NULL,
  `email` varchar(30) NOT NULL,
  PRIMARY KEY  (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

包org.test.vo如下:

package org.test.vo;

/**
 * User entity.
 *
 * @author MyEclipse Persistence Tools
 */

public class User implements java.io.Serializable {

 // Fields

 private Integer userid;
 private String username;
 private String password;
 private String email;

 // Constructors

 /** default constructor */
 public User() {
 }

 /** full constructor */
 public User(String username, String password, String email) {
  this.username = username;
  this.password = password;
  this.email = email;
 }

 // Property accessors

 public Integer getUserid() {
  return this.userid;
 }

 public void setUserid(Integer userid) {
  this.userid = userid;
 }

 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;
 }

 public String getEmail() {
  return this.email;
 }

 public void setEmail(String email) {
  this.email = email;
 }

}

 

包org.test.dao如下:

package org.test.dao;

public interface ITestDAO {
 public Object query(String HQL) throws Exception ;

}

package org.test.dao;

import java.util.List;

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

public class TestDAO extends HibernateDaoSupport implements ITestDAO{

 public Object query(String HQL) throws Exception {
  
  List list = this.getHibernateTemplate().find(HQL);
  
  return list;
 }

}

 

包org.test.service如下:

package org.test.service;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.test.dao.ITestDAO;
import org.test.vo.User;

public class LoginService {

 private ITestDAO itestdao;

 public void setItestdao(ITestDAO itestdao) {
  this.itestdao = itestdao;
 }

 public boolean userlogin(User user) throws Exception {
  boolean flag = false;
  String name = user.getUsername();
  String pwd = user.getPassword();
  String sql = "from User as t where t.username = '" + name
    + "' and t.password = '" + pwd + "'";
  List<User> list = (List<User>) itestdao.query(sql);
  System.out.println(sql);
  System.out.println(list);  
  if (list != null && list.size() > 0) {
   return true;
  } else {
   return flag;
  }
 }

}

包org.test.action如下:

package org.test.action;

import org.test.service.LoginService;
import org.test.vo.User;

public class LoginAction {

 private LoginService loginService ;
    private User user ;
 public User getUser() {
  return user;
 }

 public void setUser(User user) {
  this.user = user;
 }

 public void setLoginService(LoginService loginService) {
  this.loginService = loginService;
 }
 
 public String execute() throws Exception{
  boolean flag = loginService.userlogin(user);
  if(flag)
  {
   System.out.print("successfully");
   return "success" ;
  }else
  {
   System.out.print("failure!");
   return "failer" ;
  }
 }
}

登陆页面:

<%@ 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 'login.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>
     <h1>
   用户登陆
  </h1>
      <s:form action="login.action">  
  <s:textfield name="user.username" label="username"></s:textfield>
  <s:password name="user.password" label="password"></s:password>
  <s:submit name="submit"></s:submit>
   </s:form>
 </body>
</html>

成功页面:

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
 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>result</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>
  username:${requestScope.user.username}
  <br>
  password:${requestScope.user.password}
 </body>
</html>

失败页面:

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
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 'failer.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>
    result failer!!! <br>
  </body>
</html>

注:把上面的包连起来就构件成了这个工程,然后lib包导进去之后,就可以正常运行了。

 

 

 

 

抱歉!评论已关闭.