Struts + Hibernate 代码实例

以简单的用户登录与注册为例.本例中库名为ebusiness表名为tb_user.
需导入Struts和Hibernate相关包文件

第一步: 建库 
 create database 库名

第二步: 建表 
 create table 表名

第三步:写对应表字段的Java Bean
//DTO对象Bean
package edu.swk.struts.ebusiness.user;

public class UserBean implements java.io.Serializable{
    private int uid;
    private String uname;
    private String passwd;
    private String email;
    private String summary;

    public void setUid(int uid) {
        this.uid = uid;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }

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

    public void setSummary(String summary) {
        this.summary = summary;
    }

    public int getUid() {
        return uid;
    }

    public String getUname() {
        return uname;
    }

    public String getPasswd() {
        return passwd;
    }

    public String getEmail() {
        return email;
    }

    public String getSummary() {
        return summary;
    }
}

//持久层DTO对象Bean与上面一致
略....

第四步:配置table_name.hbm.xml文件(table_name可自定义,无需一定与表名相同)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
                                   "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<!--在该配置文件中实现tb_user表与TBUser的ORM-->
<hibernate-mapping>
<!--要使用的POJO,及对应的数据库中的表-->
<class name="edu.swk.struts.ebusiness.persist.TBUser" table="tb_user">

<!--声明主键、对应的类型及产生主键的方式-->
<id name="uid" column="uid" type="java.lang.Integer">
<generator class="identity"/>
</id>

<!--表中的其它类型声明-->
<property name="uname" column="uname" type="java.lang.String"/>
<property name="passwd" column="passwd" type="java.lang.String"/>
<property name="email" column="email" type="java.lang.String"/>
<property name="summary" column="summary" type="java.lang.String"/>
</class>
</hibernate-mapping>

第五步:配置hibernate.cfg.xml文件,此文件建立与数据库的连接(驱动、URL、用户名、密码)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
                                         "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
<hibernate-configuration>
 <session-factory name="ebusiness">
  <property name="hibernate.connection.url">
                jdbc:jtds:sqlserver://localhost:1433/ebusiness
  </property>
                <property name="hibernate.connection.driver_class">
                net.sourceforge.jtds.jdbc.Driver
  </property>
                <property name="hibernate.connection.username">
                sa
  </property>
                <property name="hibernate.connection.password">
                sa
  </property>
                <property name="dialect">
                net.sf.hibernate.dialect.SQLServerDialect
  </property>
                <property name="hibernate.show_sql">
                True
  </property>
                <property name="hibernate.use_outer_join">
                True
                </property>
                <property name="hibernate.transaction.factory_class">
                net.sf.hibernate.transaction.JDBCTransactionFactory
  </property>
  <mapping resource="edu/swk/struts/ebusiness/persist/TBUser.hbm.xml"/>
 </session-factory>
</hibernate-configuration>

第六步:JSP页面设计与实现
//主界面
<%@ page contentType="text/html; charset=GBK" %>
<html>
<head>
<title>
index
</title>
</head>
<body bgcolor="#ffffff">
<h1>
选择你要的服务
</h1>
<a href="user/login.jsp">登陆</a><br>
<a href="user/register.jsp">注册</a>
</body>
</html>

//登录界面
<%@ page contentType="text/html; charset=GBK" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<html>
<head>
<title>
login
</title>
</head>
<body bgcolor="#ffffff">
<h1>
请登陆
</h1>
<html:form action="/login.do">
用户名:<html:text property="uname"/><br />
密码:<html:password property="passwd"/><br />
<html:submit value="登陆"/>
<html:reset/>
</html:form>
</body>
</html>
//注册界面
<%@ page contentType="text/html; charset=GBK" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<html>
<head>
<title>
register
</title>
</head>
<body bgcolor="#ffffff">
<h1>
用户注册
</h1>
<html:form action="/register.do">
用户名:<html:text property="uname" size="18"/><br />
密码:<html:password property="passwd" size="18"/><br>
确认密码:<html:password property="passwd2" size="18"/><br>
邮箱:<html:text property="email" size="18"/><br>
个人介绍:<html:textarea property="summary" rows="5" cols="28"/><br>
<html:submit value="注册"/>
</html:form>
</html>

第七步:根据JSP表单信息编写Action Form Bean

package edu.swk.struts.ebusiness.user;

import java.io.*;

import javax.servlet.http.*;

import org.apache.struts.action.*;

public class UserForm extends ActionForm{
    private int uid;
    private String uname;
    private String passwd;
    private String email;
    private String summary;
    private String passwd2;

    public ActionErrors validate(ActionMapping actionMapping,
                                 HttpServletRequest httpServletRequest) {
            /** 根据需要验证表单数据. */
        return null;
    }

    public void reset(ActionMapping actionMapping,
                      HttpServletRequest servletRequest) {
  /** 重置表单数据. */
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }

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

    public void setSummary(String summary) {
        this.summary = summary;
    }

    public void setPasswd2(String passwd2) {
        this.passwd2 = passwd2;
    }

    public int getUid() {
        return uid;
    }

    public String getUname() {
        return uname;
    }

    public String getPasswd() {
        return passwd;
    }

    public String getEmail() {
        return email;
    }

    public String getSummary() {
        return summary;
    }

    public String getPasswd2() {
        return passwd2;
    }
}

第八步:持久层的实现
package edu.swk.struts.ebusiness.persist;

import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;
import org.apache.log4j.Logger;
import java.util.List;
import edu.swk.struts.ebusiness.user.UserBean;

public class UserPersist {
    private  Session session;
    private static Logger logger = Logger.getLogger(UserPersist.class);
    /**
     * 获得Hibernate环境,并取得session实例
     * @throws HibernateException
     */
    public UserPersist()throws PersistException{
        logger.info("开始进行Hibernate环境配置。");
        logger.debug("开始获取Hibernate初始化参数");
        try{
            Configuration config = new Configuration().configure();
            SessionFactory sf = config.buildSessionFactory();
            logger.debug("构建SessionFactory对象成功!");
            session = sf.openSession();
        }catch(HibernateException he){
            logger.error("发生持久异常,请通知数据库管理员");
        he.printStackTrace();
        throw new PersistException("初始化Hibernate环境时发生错误!");
        }
        logger.debug("构建Session对象成功!");
        logger.info("设置Hibernate环境成功!");
    }

    public boolean addUser(TBUser user){
        Transaction trans = null;
        logger.info("开始添加新用户!");
        try{
            logger.debug("开始用户添加事务");
            trans = session.beginTransaction();
           // session.refresh(user,LockMode.UPGRADE);
            session.save(user);
            session.flush(); //刷新cache

            trans.commit(); //提交到数据库
            logger.debug("用户添加成功!");
            return true;
        }catch(HibernateException he){
            try{
                logger.error("添加用户时发生异常!异常为:"+he.getMessage());
                trans.rollback();
                logger.info("数据库操作已撤消!");
            }catch(HibernateException he2){
            he2.printStackTrace();
            logger.fatal("发生致命错误,请通知系统管理员!");
            }
        }
         return false;
    }

    public UserBean getUser(UserBean user){
        String qname = user.getUname();
        String qpass = user.getPasswd();
        String hql = " from TBUser where uname='"+qname+"'"+" and "+" passwd='"+qpass+"'";
        List userList = null;
        try{
            userList = session.find(hql);
        }catch(HibernateException he){
            logger.error("发生持久错误,为:"+he.getLocalizedMessage());
            return null;
        }
    if(userList.size()!=0){
        TBUser tuser = (TBUser) userList.get(0);
        UserBean ruser = new UserBean();
        ruser.setUname(tuser.getUname());
        ruser.setPasswd(tuser.getPasswd());
        ruser.setSummary(tuser.getSummary());
        ruser.setEmail(tuser.getEmail());
        ruser.setUid(ruser.getUid());
        return ruser;
    }else{
        return null;
    }

    }
}

第九步:根据持久层编写代理业务Bean
package edu.swk.struts.ebusiness.user;

import edu.swk.struts.ebusiness.persist.UserPersist;
import edu.swk.struts.ebusiness.persist.PersistException;
import org.apache.log4j.Logger;

public class UserLogic {
    private static UserPersist up;
    static Logger logger = Logger.getLogger(UserLogic.class);
    static{
        try{
            logger.info("初始化数据库环境!");
            up = new UserPersist();
        }catch(PersistException he){
            logger.error("初始化数据库环境失败!,错误信息为:"+he.getMessage());
        }
    }
    public boolean login(UserBean user){
        logger.info("开始进行用户登陆逻辑处理!");
        UserBean correntUser = up.getUser(user);
        if(correntUser==null){
            logger.debug("用户不存在,登陆失败!");
            return false;
        }else{
            logger.debug("用户存在,登陆成功!");
            return true;
        }
    }

    public boolean register(UserBean user){
        return false;
    }
}

第十步:在Action中调用代理业务Bean与在表单页面中得到的数据进行操作.
package edu.swk.struts.ebusiness.user;

import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.Action;
import org.apache.log4j.Logger;

public class LoginAction extends Action {
    static Logger logger = Logger.getLogger(LoginAction.class);

    public ActionForward execute(ActionMapping mapping, ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response) {
        logger.info("开始进行用户登陆操作");
        UserForm userForm = (UserForm) form;
        UserBean ub = new UserBean();
        ub.setUname(userForm.getUname());
        ub.setPasswd(userForm.getPasswd());
        logger.debug("用户登陆信息为:");
        logger.debug("用户名:"+ub.getUname());
        logger.debug("用户密码:"+ub.getPasswd());

        UserLogic ul = new UserLogic();
        boolean done = ul.login(ub);
        if(done){
            logger.info("登陆成功,转入登陆页面");
            return mapping.findForward("loginSuccess");
        }else{
            logger.info("登陆失败!");
            return mapping.findForward("loginFailure");
        }
    }
}

第十二步:配置struts-config.xml文件,(配置Action和Action Form Bean之间的关系)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

<struts-config>
  <form-beans>
    <form-bean name="userForm" type="edu.swk.struts.ebusiness.user.UserForm" />
  </form-beans>
  <action-mappings>
    <action input="/register.jsp" name="userForm" path="/register" scope="request" type="edu.swk.struts.ebusiness.user.RegisterAction" validate="true">
      <forward name="registerSuccess" path="/user/login.jsp" />
      <forward name="registerFailure" path="/user/reg_fail.jsp" />
    </action>
    <action input="login.jsp" name="userForm" path="/login" scope="request" type="edu.swk.struts.ebusiness.user.LoginAction">
      <forward name="loginSuccess" path="/index.jsp" />
      <forward name="loginFailure" path="/user/login_fail.jsp" />
    </action>
  </action-mappings>
  <message-resources parameter="ApplicationResources" />
</struts-config>


第十三步:配置web.xml文件(一般无需进行改动)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<!-- 过滤器,解决数据与页面交互时中英文件转换问题 -->
  <filter>
    <filter-name>setencodingfilter</filter-name>
    <filter-class>edu.swk.struts.ebusiness.common.http.SetEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>gbk</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>setencodingfilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <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>2</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet>
    <servlet-name>InitConfig</servlet-name>
    <servlet-class>edu.swk.struts.ebusiness.common.ConfigServlet</servlet-class>
    <load-on-startup>3</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <taglib>
    <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
  </taglib>
  <taglib>
    <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
  </taglib>
  <taglib>
    <taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
  </taglib>
  <taglib>
    <taglib-uri>/WEB-INF/struts-template.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-template.tld</taglib-location>
  </taglib>
  <taglib>
    <taglib-uri>/WEB-INF/struts-tiles.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
  </taglib>
  <taglib>
    <taglib-uri>/WEB-INF/struts-nested.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-nested.tld</taglib-location>
  </taglib>
</web-app>

阅读更多

没有更多推荐了,返回首页