Struts2整合Hibernate3實現用戶登錄功能


         所用技術:struts2 ,hibernate,jsp,mysql

     本DEMO僅僅實現用戶登錄功能,采用MVC思想,自己也覺得相對是比較簡單,比較容易理解數據流向的一個例子,通過整合這個過程,能夠清晰的看出整個項目工程的數據流向和設計思想,是新手對於整合struts2和hibernate的最好的例子。

     現將整合思想,過程,代碼整理如下,如果新手看了還是有不明白或者需要源碼,本人樂意效勞和分享源碼。

     JSP作為視圖層V,顯示登錄,登錄成功,失敗頁面;Struts2作為控制層C處理頁面跳轉;Hibernate用作數據模型M,它與前台程序的接口以DAO形式提供。

一.數據庫設計:

  1.創建數據庫test   表名為:user

          id  int  not null 自增

          username   varchar(11) not null

          password   varchar(11 not null)

二.M層開發:   

  2.Hibernate基本配置:

     為Web項目添加Hibernate的相關jar包,hibernate.cfg.xml,並應用右擊項目文件,myeclise,add hibernate …將建立sessionfacotry.這樣就不用再自己去寫了,實現了高效開發。下為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:///test</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="connection.password">123456</property>
        <property name="connection.driver_class">org.gjt.mm.mysql.Driver</property>
        
        <!-- 在控制台顯示SQL語句 -->    
        <property name="show_sql">true</property>

        <mapping resource="com/red/vo/User.hbm.xml" />
    
    </session-factory>

</hibernate-configuration>
View Code

 

  3.生成POJO(Plain Old Java Object,簡單的Java對象,通常也稱為VO[ Value  Object ]對象,值對象)對象類 ,POJO是一種特殊的Java類,其中有一些屬性及其對應的getter/setter方法,不允許有業務方法。將User.hbm.xml配置文件一定要放在和User實體bean相同的文件目錄下。(附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" >

<hibernate-mapping package="com.red.vo">

    <class name="User" table="user">
        <id name="id" column="id" type="integer">
            <generator class="identity"/>
        </id>
 
        <property name="username" column="username" type="string" />
        <property name="password" column="password" type="string" />
    </class>
    
</hibernate-mapping>
View Code

 4.在src中另外建立兩個包,分別放DAO接口IUserDAO及其實現類UserDAO。(附IUserDAO ,UserDAO  源碼)

UserDAO.java

package com.red.dao.impl;

import java.util.List;

import javax.persistence.Query;

import com.red.dao.IUserDAO;
import com.red.factory.HibernateSessionFactory;
import com.red.vo.User;

/**
 * 實現接口
 * @author Red
 *
 */
public class UserDAO  implements IUserDAO{
    public User validateUser(String username,String password){
        String sql="from User u where u.username=? and u.password=?";
        org.hibernate.Query query=HibernateSessionFactory.getSession().createQuery(sql);
        query.setParameter(0, username);
        query.setParameter(1, password);
        List users=query.list();
        if(users.size()!=0){
            User user=(User)users.get(0);
            return user;
        }
        HibernateSessionFactory.closeSession();
        return null;
    }
}
View Code

IUserDAO.java

package com.red.dao;
import com.red.vo.User;

/**
 * 接口
 * @author Red
 *
 */
public interface IUserDAO {

    public User validateUser(String username,String password);
}
View Code

三.C層開發: 

  5.加載,配置Struts2:

     將jar包復制到lib目錄下,並且將mysql的驅動包也放進去,修改web.xml的代碼。(附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">
    
    <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>
    <display-name></display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
View Code

  6.實現Action:

     在src中新建包action,創建類LoginAction類:(附代碼LoginAction.java)

package com.red.action;

import com.opensymphony.xwork2.ActionSupport;
import com.red.dao.IUserDAO;
import com.red.dao.impl.UserDAO;
import com.red.vo.User;

/**
 * 用戶登錄action
 * @author Red
 *
 */
public class LoginAction extends ActionSupport{
    private String username;
    private String password;
    //處理用戶請求的execute方法
    public String execute() throws Exception{
        boolean validated=false;//驗證成功標識
        IUserDAO userDAO=new UserDAO();
        User user=userDAO.validateUser(getUsername(),getPassword());
        
        if(user!=null)
        {
          validated=true;        
        }
        if(validated)
        {
           //驗證成功返回字符串“success”
            return SUCCESS;
        }
        else
        {
            //驗證失敗返回字符串“error”
            return ERROR;
        }
    }
    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;
    }
    
}
View Code

 7.在struts.xml 中配置action:(附代碼:struts.xml)

<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">
   <struts>
     <package name="struts" extends="struts-default">
       <action name="login" class="com.red.action.LoginAction">
         <result name="success">/welcome.jsp</result>
         <result name="error">/error.jsp</result>
       </action>
     </package>
   </struts>
View Code

四.V層開發:

      就是寫當個JSP文件。源碼序列分別是:index.jsp;welcome.jsp;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>login</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.action" method="post">
      用戶名:<input type="text" name="username"/><br/>
      密碼:<input type="password" name="password"/><br/>
      <input type="submit" value="登 錄">
    </form>
  </body>
</html>
View Code

 

<%@ 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>welcome</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="username"/>,您好!歡迎光臨RED‘S HOME.
  </body>
</html>
View Code

 

<%@ 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>error</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>
    登錄失敗! <br>
  </body>
</html>
View Code

 

    歡迎大神拍磚,新手朋友:我們可以一起學習學習呃。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM