Struts+DAO+Hibernate搭建完成!(源码)

昨天搭了这个框架实现用户登录,很高兴!同时也遇到了一些问题。不过总算完成了。

搭建环境:MyEclipse+Mysql

实现用户登录,以下为步骤:

1.在mysql中建立一个名为person的表。
表中数据:id varchar(32) no null primary key;
              name varchar(20) no null;
              password varchar(20) no null;
             
2.打开MyEclipse,从菜单中选择窗口,选择首选项,选择数据库浏览器。

3.配置数据库驱动(mysql-connector-java-5.1.6-bin.jar)。

4.选菜单的窗口,选择显示视图,选择其它,选MyEclipse中的DB Browser。点确定。从新窗口中选择New,连接数据库MySQL。

5.新建一个webproject,命名为SHLogin,加入Add Hibernate Capabilities...,选择Hibernate3.1,Next---Next----选择Mysql----Next----不创建工厂----Finish

6.src下新建接口cn.mldn.lxh.login6.dao,命名PersonDAO,写入代码如下:

package cn.mldn.lxh.login6.dao;

import cn.mldn.lxh.login6.vo.Person;

public interface PersonDAO {
 public boolean isLogin(Person person) throws Exception ;
}


7.在src下新建一个类,包名cn.mldn.lxh.login6.vo,类名为Person,写入代码:

package cn.mldn.lxh.login6.vo;

public class Person {
private String id;
private String name;
private String password;
public String getId() {
 return id;
}
public void setId(String id) {
 this.id = id;
}
public String getName() {
 return name;
}
public void setName(String name) {
 this.name = name;
}
public String getPassword() {
 return password;
}
public void setPassword(String password) {
 this.password = password;
}

}

8.在src下新建包名cn.mldn.lxh.login6.impl,类名LoginDAOImpl,覆写全部抽象方法。写入代码:

package cn.mldn.lxh.login6.impl;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import cn.mldn.lxh.login6.dao.PersonDAO;
import cn.mldn.lxh.login6.factory.DefaultSessionFactory;
import cn.mldn.lxh.login6.vo.Person;

public class PersonDAOImpl implements PersonDAO {
    private Session session;
    public PersonDAOImpl()
    {
     this.session=DefaultSessionFactory.getSession();
    }
 public boolean isLogin(Person person) throws Exception {
  boolean flag=false;
  String hql="FROM Person AS p WHERE p.id=? AND p.password=?";
  Query q= this.session.createQuery(hql);
  //设置查询参数
  q.setString(0, person.getId());
  q.setString(1,person.getPassword());
  
  Iterator iter=q.list().iterator();
  if(iter.hasNext())
  {
   //修改成功标记
   flag=true;
   //从查找出的对象取出名字
   person.setName(((Person) iter.next()).getName());
  }
  //关闭session连接
  this.session.close();
  return flag;
  
 }

}

9.在src下新建工厂类cn.mldn.lxh.login6.factory,类名DAOFactory

package cn.mldn.lxh.login6.factory;

import cn.mldn.lxh.login6.dao.PersonDAO;
import cn.mldn.lxh.login6.impl.PersonDAOImpl;

public class DAOFactory {
public static PersonDAO getPersonDAOInstance()
{
 
 return new PersonDAOImpl();
 
}
}

10.建立映射文件:点表person右键,选择Create Hibernate Mapping,创建在包cn.mldn.lxh.login6.vo下,下面第一个方块打钩,Next----主键生成方式:assigned,完成。

11.修改映射文件Person.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="cn.mldn.lxh.login6.vo.Person" table="person" catalog="people">
        <id name="id" type="java.lang.String">
            <column name="id" length="32" />
            <generator class="assigned" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" length="20" not-null="true" />
        </property>
        <property name="password" type="java.lang.String">
            <column name="password" length="20" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

12.工厂包内新建一个类,命名DefaultSessionFactory,写入代码:

package cn.mldn.lxh.login6.factory;

import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

public class DefaultSessionFactory {
public static Session getSession()
{
 Session session=null;
 session =new Configuration().configure().buildSessionFactory().openSession();
    return session;
}
}

13.映射文件中选择show_sql---true

14.包cn.mldn.lxh.login6.vo下新建测试类(测试是否能连接数据库),类名TestDAO,主方法输出,写入代码:

package cn.mldn.lxh.login6.vo;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import cn.mldn.lxh.login6.factory.DAOFactory;
import cn.mldn.lxh.login6.factory.DefaultSessionFactory;

public class TestDAO {

 /**
  * @param args
  * @throws Exception
  */
 public static void main(String[] args) throws Exception {
  
  Session session = DefaultSessionFactory.getSession();
  Person p=new Person();
  p.setId("123456");
  p.setPassword("123456");
  String hql="FROM Person AS p WHERE p.id=? AND p.password=?";
  Query q= session.createQuery(hql);
  //设置查询参数
  q.setString(0, p.getId());
  q.setString(1,p.getPassword());
  List list = q.list();
  System.out.println(list.size());
  Iterator iter=q.list().iterator();
  System.out.println(DAOFactory.getPersonDAOInstance().isLogin(p));
 }

}

15.项目添加Struts支持,包名cn.mldn.lxh.login6.struts。完成

16.添加一个JSP页面,名为login.jsp。Template to use:Standard JSP using Struts 1.2。代码修改如下:

<%@ page language="java" pageEncoding="GbK"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
<html:html lang="true">
  <head>
    <title>登陆程序 —— Struts + DAO + Hibernate</title>
  </head>
 
  <body>
 <center>
  <h1>登陆程序 —— Struts + DAO + Hibernate</h1>
  <hr>
  <br>
  <html:errors/>
  <logic:present name="flag" scope="request">
   <logic:equal name="flag" value="true">
    <h2>登陆成功!!!</h2>
    <h2>欢迎<font color="red">${person.name}</font>光临!!!</h2>
   </logic:equal>
   <logic:equal name="flag" value="false">
    <h2>登陆失败!!!</h2>
    <h2>错误的用户ID或密码!!!</h2>
   </logic:equal>
  </logic:present>
  <br>
  <html:form action="login.do" method="post">
   用户ID:<html:text property="id"/><br>
   密&nbsp;&nbsp;码:<html:password property="password"/><br>
   <input type="hidden" name="status" value="login">
   <html:submit value="登陆"/>
   <html:reset value="重置"/>
  </html:form>
 </center>
  </body>
</html:html>

17.选择自定义透视图(Custonize Perspective)
选择struts 1.2,建立Struts 1.2 Form,Action&JSP

18.在src下建立Struts 1.2 Form,Action_JSP,Use case:login,Superclass:org.apache.struts.action.ActionForm,
添加Form Properties,name和password----->next----->Finish

19.修改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="loginForm"
   type="cn.mldn.lxh.login6.struts.form.LoginForm" />

 </form-beans>

 <global-exceptions />
 <global-forwards />
 <action-mappings>
  <action attribute="loginForm" input="/login.jsp"
   name="loginForm" path="/login" scope="request"
   type="cn.mldn.lxh.login6.struts.action.LoginAction"
   parameter="status">
   <forward name="suc" path="/login.jsp"></forward>
   <forward name="fal" path="/login.jsp"></forward>
  </action>

 </action-mappings>

 <message-resources
  parameter="cn.mldn.lxh.login6.struts.ApplicationResources" />
</struts-config>

20.修改ApplicationResources.properties的代码,实现错误输出。

# Resources for parameter 'cn.mldn.lxh.login6.struts.ApplicationResources'
# Project SHLogin
id.null = <li>\u7528\u6237ID\u4e0d\u80fd\u4e3a\u7a7a\uff01\uff01\uff01
password.null = <li>\u7528\u6237\u5bc6\u7801\u4e0d\u80fd\u4e3a\u7a7a\uff01\uff01\uff01


21.修改LoginForm.java,代码如下:

/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package cn.mldn.lxh.login6.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;
import org.apache.struts.action.ActionMessage;

/**
 * MyEclipse Struts Creation date: 03-12-2007
 *
 * XDoclet definition:
 *
 * @struts.form name="loginForm"
 */
public class LoginForm extends ActionForm {
 /*
  * Generated fields
  */

 /** password property */
 private String password;

 /** name property */
 private String name;

 /** id property */
 private String id;

 private String status;

 // 如果status的值为login,则表示要验证ID和password

 /*
  * Generated Methods
  */

 /**
  * Method validate
  *
  * @param mapping
  * @param request
  * @return ActionErrors
  */
 public ActionErrors validate(ActionMapping mapping,
   HttpServletRequest request) {
  ActionErrors errors = new ActionErrors();
  if ("login".equals(this.status)) {
   if (this.id == null || "".equals(this.id)) {
    errors.add("id", new ActionMessage("id.null"));
   }
   if (this.password == null || "".equals(this.password)) {
    errors.add("password", new ActionMessage("password.null"));
   }
  }
  return errors;
 }

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

 /**
  * Returns the password.
  *
  * @return String
  */
 public String getPassword() {
  return password;
 }

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

 /**
  * Returns the name.
  *
  * @return String
  */
 public String getName() {
  return name;
 }

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

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

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

 public String getStatus() {
  return status;
 }

 public void setStatus(String status) {
  this.status = status;
 }
}

22.修改LoginAction,代码如下:

* Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package cn.mldn.lxh.login6.struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import cn.mldn.lxh.login6.factory.DAOFactory;
import cn.mldn.lxh.login6.struts.form.LoginForm;
import cn.mldn.lxh.login6.vo.Person;

/**
 * MyEclipse Struts Creation date: 03-12-2007
 *
 * XDoclet definition:
 *
 * @struts.action path="/login" name="loginForm" input="/form/login.jsp"
 *                scope="request" validate="true"
 */
public class LoginAction extends DispatchAction {
 /*
  * Generated Methods
  */

 /**
  * Method execute
  *
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return ActionForward
  */
 public ActionForward login(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response) {
  LoginForm loginForm = (LoginForm) form;
  // 从ActionForm中取出要的内容
  Person person = new Person();
  person.setId(loginForm.getId());
  person.setPassword(loginForm.getPassword());
  boolean flag = false;
  
  try {
   flag = DAOFactory.getPersonDAOInstance().isLogin(person);
  } catch (Exception e) {
   e.printStackTrace();
  }
  request.setAttribute("flag", new Boolean(flag));
  if (flag) {
   // 如果成功,则将person对象传递过去
   request.setAttribute("person", person);
   return mapping.findForward("suc");
  } else {
   return mapping.findForward("fal");
  }
 }
}

23.运行MyEclipse内的Tomcat。运行框架。完成!!!

施杨出品!!!

posted on 2008-07-15 10:38  俱正Steven  阅读(1510)  评论(5编辑  收藏  举报

导航