struts1&&Hibernate Demo1

用struts1和Hibernate實現簡單登錄案例

主要思路:通過用戶名name驗證 如果一致則驗證成功。

附上源碼:

1.建立student表,這裏使用的是mysql數據庫,以下爲該表的DDL:

    create table `test`.`student`(
        `sid` INT not null auto_increment,
       `sname` VARCHAR(64),
       `email` VARCHAR(32),
        primary key (`sid`)
    );

    create unique index `PRIMARY` on `test`.`student`(`sid`);

並插入一條記錄:

  insert into student(sname,email) values('xwj','[email protected]');

 

2.建立web工程,引入struts1.2包和hibernate3.3包

3.反向工程建立form和*.hbm.xml 以及HibernateSessionFactory文件(也叫PO)。(當然form也可以使用struts-config.xml自動構建,這裏我是使用這種方法,不過建議使用第一種)

/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package com.xwj.struts.form;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

/** 
 * MyEclipse Struts
 * Creation date: 11-12-2014
 * 
 * XDoclet definition:
 * @struts.form name="studentForm"
 */
public class StudentForm extends ActionForm {
    /*
     * Generated fields
     */

    /** id property */
    private Integer id;

    /** email property */
    private String email;

    /** name property */
    private String name;

    /*
     * Generated Methods
     */

    /** 
     * Method validate
     * @param mapping
     * @param request
     * @return ActionErrors
     */
    public ActionErrors validate(ActionMapping mapping,
            HttpServletRequest request) {
        // TODO Auto-generated method stub
        return null;
    }

    /** 
     * Method reset
     * @param mapping
     * @param request
     */
    public void reset(ActionMapping mapping, HttpServletRequest request) {
        // TODO Auto-generated method stub
    }

    /** 
     * Returns the id.
     * @return Integer
     */
    public Integer getId() {
        return id;
    }

    /** 
     * Set the id.
     * @param id The id to set
     */
    public void setId(Integer id) {
        this.id = id;
    }

    /** 
     * Returns the email.
     * @return String
     */
    public String getEmail() {
        return email;
    }

    /** 
     * Set the email.
     * @param email The email to set
     */
    public void setEmail(String email) {
        this.email = email;
    }

    /** 
     * Returns the name.
     * @return String
     */
    public String getName() {
        System.out.println("StudentForm.getName()"+name);
        return name;
    }

    /** 
     * Set the name.
     * @param name The name to set
     */
    public void setName(String name) {
        this.name = name;
    }
}

student.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="com.xwj.struts.form.StudentForm" table="student"
        catalog="test">
        <id name="id" type="java.lang.Integer">
            <column name="sid" />
            <generator class="increment" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="sname" length="64" />
        </property>
        <property name="email" type="java.lang.String">
            <column name="email" length="32" />
        </property>
    </class>
</hibernate-mapping>

HibernateSessionFactory.java

package com.xwj.hibernate;

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

}
View Code

另外附上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="dialect">
            org.hibernate.dialect.MySQLDialect
        </property>
        <property name="connection.url">jdbc:mysql:///test</property>
        <property name="connection.username">xiaoming</property>
        <property name="connection.password">xiaoming</property>
        <property name="connection.driver_class">
            com.mysql.jdbc.Driver
        </property>
        <property name="myeclipse.connection.profile">mysql</property>
        <mapping resource="com/xwj/hibernate/Student.hbm.xml" />
    </session-factory>
</hibernate-configuration>
View Code

 

3.通過配置文件struts-config.xml實現自動建Action,並且把關鍵邏輯代碼寫入這裏:

LoginAction.java

/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package com.xwj.struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.xwj.hibernate.HibernateSessionFactory;
import com.xwj.struts.form.StudentForm;

/** 
 * MyEclipse Struts
 * Creation date: 11-12-2014
 * 
 * XDoclet definition:
 * @struts.action input="/index.jsp" validate="true"
 */
public class LoginAction extends Action {
    /*
     * Generated Methods
     */

    /** 
     * Method execute
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     */
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
        // TODO Auto-generated method stub
        System.out.println("LoginAction.execute()");
        StudentForm student = (StudentForm) form;
        System.out.println("name= "+student.getName());
        
        Session session =HibernateSessionFactory.getSession();
        Transaction tx=session.beginTransaction();
        StudentForm s = (StudentForm) session.load(StudentForm.class, 1);
        System.out.println(1);
        System.out.println("hibernate name:"+s.getName());
    //    tx.commit();
        System.out.println(2);
        if(s.getName().equals(student.getName())){
            System.out.println(3);
            return mapping.findForward("success");
        }else{
            System.out.println(4);
        return mapping.findForward("error");
    }
    }
}

 

附上struts-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">

<struts-config>
  <data-sources />
  <form-beans >
    <form-bean name="studentForm" type="com.xwj.struts.form.StudentForm" />

  </form-beans>

  <global-exceptions />
  <global-forwards />
  <action-mappings >
    <action
      attribute="studentForm"
      input="/WEB-INF/student.jsp"
      name="studentForm"
      path="/login"
      scope="request"
      type="com.xwj.struts.action.LoginAction">
      <set-property property="cancellable" value="true" />
      <forward name="error" path="/WEB-INF/error.jsp" />
      <forward name="success" path="/WEB-INF/wel.jsp" />
    </action>

  </action-mappings>

  <message-resources parameter="com.xwj.struts.ApplicationResources" />
</struts-config>

 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name /> <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <init-param> <param-name>debug</param-name> <param-value>3</param-value> </init-param> <init-param> <param-name>detail</param-name> <param-value>3</param-value> </init-param> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>

4.編寫jsp頁面層:

index.jsp(input source)

   <form action="login.do" >
    name:<input type="text" name="name"><br>
    email:<input type="text" name="email"><br>
    <input type="submit" value="submit">
    
    </form>

跳轉頁面wel.jsp 以及error.jsp

 <body>
    This is wel JSP page. <br>
    hello<%=request.getParameter("name") %>
    <br>
  your email is
<%=request.getParameter("email") %> </body>

 

到這裏,大功告成!如果期間遇到問題,建議慢慢來構建工程,我個人先是驗證Hibernate配置是否有錯,建了testMain文件:

package com.xwj.hibernate;

import org.hibernate.Session;

import com.xwj.struts.form.StudentForm;

public class TestMain {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
    /*    //test hibernate 
        Session session = HibernateSessionFactory.getSession();
        StudentForm student = (StudentForm) session.load(StudentForm.class, 1);
        System.out.println("name:"+student.getName());
        System.out.println("email:"+student.getEmail());*/
    }

}

確認沒問題在驗證struts,如此這樣,得到解決問題的方法。

接下來要慢慢完善,1.數據庫的取數據是很有問題的,需要實現通過用戶名和密碼去匹配,另外再添加註冊功能。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章