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

}

另外附上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>

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.数据库的取数据是很有问题的,需要实现通过用户名和密码去匹配,另外再添加注册功能。

时间: 2024-12-07 19:05:46

struts1&&Hibernate Demo1的相关文章

struts2&amp;&amp;Hibernate Demo1

这篇文章和<struts1&&Hibernate Demo1>基本类似,我这里只是拷贝代码了. 最核心的代码:LoginAction.java package action; import org.hibernate.Session; import org.hibernate.Transaction; import hibernate.HibernateSessionFactory; import com.opensymphony.xwork2.ActionSupport; p

【转】pringMVC+Hibernate+Spring 简单的一个整合实例

ref:http://langgufu.iteye.com/blog/2088355 SpringMVC又一个漂亮的web框架,他与Struts2并驾齐驱,Struts出世早而占据了一定优势,我在博客<Struts1+Hibernate+Spring整合实例>中做了一个简单的实例,介绍了SSH1的基本搭建方式,Struts2是根据Struts1发展而来,博客中就没有贴SSH2的例子,只对比了下Struts1和Struts2异同,通过对比,SSH2的搭建基本不在话下了.下面同样做一个简单的应用实

Hibernate的核心API ---- 入门学习

叙:学习hibernate是必不可少的要了解其核心的API,下面电虫就核心API进行记录学习: Hibernate核心API Hibernate核心API有configuration.SessonFactory.Session.Transaction等,在Session中有增删改查等小地API,下面进行详细学习: 学习要有目标有方向,所以从一段代码中从上到下的进行研读不失为一种高效率的学习方法,学习模板代码如下所示: 1 package com.java.hibernate.demo1; 2 3

Hibernate(四) - HQL_QBC查询详解--抓取策略优化机制

Hibernate 的查询方式 在 Hibernate 中提供了很多种的查询的方式.Hibernate 共提供了五种查询方式. 1.Hibernate 的查询方式:OID 查询 OID检索:Hibernate根据对象的OID(主键)进行检索. ① 使用 get 方法 Customer customer = session.get(Customer.class,1l); ② 使用 load 方法 Customer customer = session.load(Customer.class,1l)

Hibernate总结1

1.Hibernate是什么 1.java持久层的一个框架 2.一个开放源代码的ORM(Object Relation Mapping,对象关系映射)框架,使得java开发人员可以使用面向对象编程的思想来操作数据库 所谓的ORM就是利用描述对象和数据库表之间的映射的元数据,自动把Java应用程序中的对象持久化到关系型数据库的表中 2.创建映射文件 实体类Customer映射到Hibernate中的cst_customer表中 1 <?xml version="1.0" encod

3、Hibernate的多表关联

一.数据库中的表关系: 一对一关系 一个人对应一张身份证,一张身份证对应一个人,一对一关系是最好理解的一种关系,在数据库建表的时候可以将人表的主键放置与身份证表里面,也可以将身份证表的主键放置于人表里面 一对多关系 一个班级拥有多个学生,一个学生只能够属于某个班级,班级是1端,学生是多端,结合面向对象的思想,1端是父亲,多端是儿子,所以多端具有1端的属性,也就是说多端里面应该放置1端的主键,那么学生表里面应该放置班级表里面的主键 多对多关系 一个学生可以选修多门课程,一个课程可以被多个学生选修,

IT视频课程集

马哥Linux培训视频课程:http://pan.baidu.com/s/1pJwk7dp Oracle.大数据系列课程:http://pan.baidu.com/s/1bnng3yZ 天善智能BI培训视频课程:http://pan.baidu.com/s/1pJ7FPXp 老方块Oracle培训全套课程:http://pan.baidu.com/s/1gdkpHxL Mysql培训课程:http://pan.baidu.com/s/1c0vliMW Oracle数据库性能优化实务课程视频+源码

IT视频课程集(包含各类Oracle、DB2、Linux、Mysql、Nosql、Hadoop、BI、云计算、编程开发、网络、大数据、虚拟化

马哥Linux培训视频课程:http://pan.baidu.com/s/1pJwk7dp Oracle.大数据系列课程:http://pan.baidu.com/s/1bnng3yZ 天善智能BI培训视频课程:http://pan.baidu.com/s/1pJ7FPXp 老方块Oracle培训全套课程:http://pan.baidu.com/s/1gdkpHxL Mysql培训课程:http://pan.baidu.com/s/1c0vliMW Oracle数据库性能优化实务课程视频+源码

[转]百度云视频(希望我和大家一起进步)

马哥Linux培训视频课程:http://pan.baidu.com/s/1pJwk7dp Oracle.大数据系列课程:http://pan.baidu.com/s/1bnng3yZ 天善智能BI培训视频课程:http://pan.baidu.com/s/1pJ7FPXp 老方块Oracle培训全套课程:http://pan.baidu.com/s/1gdkpHxL Mysql培训课程:http://pan.baidu.com/s/1c0vliMW Oracle数据库性能优化实务课程视频+源码