JSP+Hibernate入门级实例--留言系统

本文介绍了一个基于JSP和Hibernate技术实现的简单留言系统。该系统采用准三层架构,重点介绍了Hibernate的使用,并详细展示了项目的目录结构及关键代码片段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

      这是个用JSP+Hibernate编写的非常简单的留言系统例子,是个准三层结构(因为为了节省时间着重介绍hibernate部分,省去的service层,转而使用jsp页面进行业务处理,但并不是在jsp页面上过多的编写java代码,而是使用专门的jsp作为业务处理层) 

开发工具:MyEclipse+Mysql

目录结构如下:

config(配置类)

    BeanConfig.java
    MessageConfig.java

constants(常量类)

   Constants.java

dao(数据访问类)
  
    hibernate
        MessageDAO.java
        UserDAO.java
    IMessageDAO.java
    IUserDAO.java
   

exception(异常类)
    MessageAuthorityException.java
    MessageDAOException.java
    MessageException.java

model(模型类)
    Message.hbm.xml
    Message.java
    User.hbm.xml
    User.java

sql (数据库脚本)
   scrip.sql

util(工具类)
    DaoFactory.java
    HibernateDAO.java
    HibernateFilter.java
    HibernateUtil.java

 

BeanConfig.java

package cn.hxex.message.config;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;

import cn.hxex.message.exception.MessageException;

public class BeanConfig 
{
    
private String id;
    
private String type;

    
public String getId() {
        
return id;
    }

    
public void setId(String id) {
        
this.id = id;
    }

    
    
public String getType() {
        
return type;
    }

    
public void setType(String type) {
        
this.type = type;
    }
    
    
    
private Object instance;
    
public Object getInstance() 
    
{
        
ifnull!=instance ) return instance;
        
        
try
        
{
            Class cls 
= Class.forName( getType() );
            instance 
= cls.newInstance();
            
return instance;
        }

        
catch( Exception ex )
        
{
            
throw new MessageException( "Couldn't find class:" + getType() );
        }

    }

    
    
public String toString()
    
{
        
return ReflectionToStringBuilder.toString( this );
    }

}

MessageConfig

package cn.hxex.message.config;

import java.util.Hashtable;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;

import cn.hxex.message.exception.MessageException;

/**
 * 系统配置信息类
 
*/

public class MessageConfig
{
    
public static Hashtable beans;

    
/**
     * 构造函数
     
*/

    
public MessageConfig()
    
{
        beans 
= new Hashtable();
    }


    
/**
     * 增加一个BeanConfig对象
     * 
@param bean
     
*/

    
public void addBean(BeanConfig bean)
    
{
        beans.put(bean.getId(), bean);
    }


    
/**
     * 得到一个DAO接口对象的实例
     * 
@param name DAO接口对象的名称
     * 
@return 指定DAO接口的实现类的实例
     
*/

    
public Object getBean(String name)
    
{
        BeanConfig config 
= (BeanConfig) beans.get(name);

        
if (config == null)
        
{
            
throw new MessageException("Couldn't find the bean: " + name);
        }


        
return config.getInstance();
    }


    
public String toString()
    
{
        
return ReflectionToStringBuilder.toString(this);
    }

}

Constants

package cn.hxex.message.constants;

public class Constants {
    
public static final String SESSION_USER = "cn.hxex.message.user";
}

 

IMessageDAO

package cn.hxex.message.dao;

import java.util.List;

import cn.hxex.message.model.Message;

public interface IMessageDAO 
{
    
public void saveMessage( Message message );
    
public void updateMessage( Message message );
    
public List getMessages( );
    
public void deleteMessage( String id, String userId );
    
public Message getMessage( String id );
}

IUserDAO

 

package cn.hxex.message.dao;

import cn.hxex.message.model.User;

public interface IUserDAO 
{
    
public void saveUser( User user );
    
public User getUser( String username );
    
public User getUserById( String id );
}

 

MessageDAO

package cn.hxex.message.dao.hibernate;

import java.util.List;

import cn.hxex.message.dao.IMessageDAO;
import cn.hxex.message.exception.MessageDAOException;
import cn.hxex.message.model.Message;
import cn.hxex.message.util.HibernateDAO;

/**
 * IMessageDAO接口的Hibernate实现
 
*/

public class MessageDAO extends HibernateDAO implements IMessageDAO
{

    
/**
     * 保存留言信息
     * 
     * 
@param message
     *            被保存的留言对象
     
*/

    
public void saveMessage(Message message)
    
{
        
super.saveObject(message);
    }


    
/**
     * 得到所有的留言信息
     * 
     * 
@return 返回所有的留言信息
     
*/

    
public List getMessages()
    
{
        String hsql 
= "from Message";
        
return super.getObjects(hsql);
    }


    
/**
     * 删除留言信息
     * 
     * 
@param id
     *            要删除的留言信息的ID值
     * 
@param userId
     *            执行删除操作的用户ID
     
*/

    
public void deleteMessage(String id, String userId)
    
{
        Message msg 
= getMessage(id);
        
if (msg == null)
        
{
            
throw new MessageDAOException("找不到你所要删除的留言!");
        }


        
if (!msg.getUser().getId().equals(userId))
        
{
            
throw new MessageDAOException("你不能删除别人的留言!");
        }


        deleteObject(msg);
    }


    
/**
     * 得到留言信息
     * 
     * 
@param id
     *            留言的ID值
     * 
@return 指定ID值得留言对象
     
*/

    
public Message getMessage(String id)
    
{
        
return (Message) getObject(Message.class, id);
    }


    
/**
     * 更新留言信息
     * 
     * 
@param message
     *            欲更新的留言对象
     
*/

    
public void updateMessage(Message message)
    
{
        updateObject(message);
    }


}


UserDAO
package cn.hxex.message.dao.hibernate;

import cn.hxex.message.dao.IUserDAO;
import cn.hxex.message.exception.MessageDAOException;
import cn.hxex.message.model.User;
import cn.hxex.message.util.HibernateDAO;

/**
 * IUserDAO接口的Hibernate实现
 
*/

public class UserDAO extends HibernateDAO implements IUserDAO
{

    
/**
     * 保存用户信息到数据库
     * 
@param user 被保存的用户对象
     
*/

    
public void saveUser(User user)
    
{
        
if (user == null)
            
return;

        User u 
= getUser(user.getName());
        
if (u != null)
            
throw new MessageDAOException("用户名已经存在,请使用其它用户名!");

        saveObject(user);
    }


    
/**
     * 得到用户对象
     * 
@param username 用户的登录名
     * 
@return 指定登录名的用户对象
     
*/

    
public User getUser(String username)
    
{
        User u 
= (User) getObject("from User u where u.name = '" + username
                
+ "'");
        
return u;
    }


    
/**
     * 得到用户对象的信息
     * 
@param id 用户的ID值
     * 
@return 指定的用户信息
     
*/

    
public User getUserById(String id)
    
{
        
return (User) getObject(User.class, id);
    }


}

 

MessageAuthorityException

package cn.hxex.message.exception;

public class MessageAuthorityException extends MessageException 
{
    
private static final long serialVersionUID = 1L;

    
public MessageAuthorityException(String message) 
    
{
        
super(message);
    }


}


MessageDAOException
package cn.hxex.message.exception;

public class MessageDAOException extends MessageException 
{

    
private static final long serialVersionUID = 2L;

    
public MessageDAOException(String message) 
    
{
        
super(message);
    }



}


MessageException
package cn.hxex.message.exception;

public class MessageException extends RuntimeException 
{

    
/**
     * Generated serialVersionUID
     
*/

    
private static final long serialVersionUID = 6905209869067708768L;

    
public MessageException( String message )
    
{
        
super( message );
    }

}

 

Message.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
>
<hibernate-mapping package="cn.hxex.message.model"> 

    
<class name="Message" table="MESSAGE">
    
        
<id name="id" column="ID" type="string">
           
<generator class="uuid.hex"/>
        
</id>
        
        
<property name="title" column="TITLE"/>
        
        
<property name="content" column="CONTENT" />
        
        
<many-to-one name="user"   column="USER_ID"/>
        
    
</class>
    
</hibernate-mapping>

 

User.hbm.xml

 

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
>
<hibernate-mapping package="cn.hxex.message.model"> 

    
<class name="User" table="USERINFO">
    
        
<id name="id" column="ID" type="string">
           
<generator class="uuid.hex"/>
        
</id>
        
        
<property name="name" column="NAME"/>
        
        
<property name="password" column="PASSWORD" />
        
        
<set name="messages" inverse="true" cascade="save-update" >
            
<key column="USER_ID"/>
            
<one-to-many class="Message"/>
        
</set>
        
    
</class>
    
</hibernate-mapping>

 

Message

package cn.hxex.message.model;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;

public class Message {

    
private     String     id;
    
private        String    title;
    
private        String    content;
    
private     User    user;
    
    
public String getContent() 
    
{
        
return content;
    }

    
public void setContent(String content) 
    
{
        
this.content = content;
    }


    
public String getId() {
        
return id;
    }

    
public void setId(String id) 
    
{
        
this.id = id;
    }


    
public String getTitle() 
    
{
        
return title;
    }

    
public void setTitle(String title) 
    
{
        
this.title = title;
    }


    
public User getUser() 
    
{
        
return user;
    }

    
public void setUser(User user) 
    
{
        
this.user = user;
    }


    
public String toString()
    
{
        
return ReflectionToStringBuilder.toString( this );
    }

    
    
public int hashcode()
    
{
        
if( id!=null )
            
this.id.hashCode();
        
return 0;
    }

    
    
public boolean equals( Object obj )
    
{
        
if( obj==null ) return false;
        
        
ifthis==obj ) return true;
        
        
if( obj instanceof Message )
        
{
            
ifthis.id!=null )
                
return this.id.equals( ((Message)obj).getId() );
        }

        
return false;
    }

}

 

 

User
package cn.hxex.message.model;

import java.util.Set;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;


public class User {

    
private     String     id;
    
private     String     name;
    
private     String     password;
    
private     Set     messages;

    
public String getId() {
        
return id;
    }

    
public void setId(String id) {
        
this.id = id;
    }


    
public Set getMessages() {
        
return messages;
    }

    
public void setMessages(Set messages) {
        
this.messages = messages;
    }


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

    
    
public String toString()
    
{
        
return ReflectionToStringBuilder.toString( this );
    }

    
    
public boolean equals( Object obj )
    
{
        
if( obj==null ) return false;
        
        
ifthis==obj ) return true;
        
        
if( obj instanceof User )
        
{
            
ifthis.id!=null )
                
return this.id.equals( ((User)obj).getId() );
        }

        
return false;
    }

}

 

 

create table userinfo(
  id 
varchar(32not null,
  name 
varchar(32not null,
  password 
varchar(32not null,
  
constraint userinfo_pk primary key(id),
  
constraint userinfo_unique_name unique(name)
);


create table message(
  id 
varchar(32not null,
  title 
varchar(32not null,
  content 
varchar(2000),
  
user_id varchar(32),
  
constraint message_pl primary key(id),
  
constraint message_user_fk foreign key(user_idreferences userinfo(id)
) ENGINE
=InnoDB DEFAULT CHARSET=gb2312;

 

DaoFactory

package cn.hxex.message.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.digester.Digester;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.SAXException;

import cn.hxex.message.config.MessageConfig;

public class DaoFactory 
{
    
private static Log log = LogFactory.getLog(DaoFactory.class);

    
public static final MessageConfig messageConfig;
    
    
static
    
{
        Digester digester 
= new Digester();
        digester.setValidating( 
false );
        
        digester.addObjectCreate( 
"config""cn.hxex.message.config.MessageConfig" );
        digester.addSetProperties( 
"config" );
        
        digester.addObjectCreate( 
"config/bean""cn.hxex.message.config.BeanConfig" );
        digester.addSetProperties( 
"config/bean" );
        digester.addSetNext( 
"config/bean""addBean""cn.hxex.message.config.BeanConfig" );
        
        ClassLoader classLoader 
= Thread.currentThread().getContextClassLoader();
        InputStream in 
= classLoader.getResourceAsStream( "MessageConfig.xml" );
        MessageConfig config 
= null;
        
try {
            
if( in!=null )
                config 
= (MessageConfig)digester.parse( in );
        }
 catch (IOException e) {
            e.printStackTrace();
        }
 catch (SAXException e) {
            e.printStackTrace();
        }

        messageConfig 
= config;
    }

    
    
public static Object getDao( String name )
    
{
        
ifnull==messageConfig ) return null;
        
        
return messageConfig.getBean( name );
    }

}

 

 

HibernateDAO
package cn.hxex.message.util;

import java.util.List;

/**
 * 使用Hibernate实现DAO的基础类
 * 包括了持久化操作的一些基础方法
 
*/

public class HibernateDAO
{
    
/**
     * 保存对象信息到数据库
     * 
@param obj 需要进行持久化操作的对象
     
*/

    
public void saveObject(Object obj)
    
{
        HibernateUtil.getCurrentSession().save(obj);
    }


    
/**
     * 更新持久化对象
     * 
@param obj 需要更新的对象
     
*/

    
public void updateObject(Object obj)
    
{
        HibernateUtil.getCurrentSession().update(obj);
    }


    
/**
     * 使用HQL语句进行查询
     * 
@param hsql 查询语句
     * 
@return 符合条件的对象集合
     
*/

    
public List getObjects(String hsql)
    
{
        List result 
= HibernateUtil.getCurrentSession().createQuery(hsql)
                .list();
        
return result;
    }


    
/**
     * 使用HQL语句进行对象的查询
     * 
@param hsql 查询语句
     * 
@return 符合条件的对象
     
*/

    
public Object getObject(String hsql)
    
{
        Object result 
= HibernateUtil.getCurrentSession().createQuery(hsql)
                .uniqueResult();
        
return result;
    }


    
/**
     * 根据ID值得到持久化的对象
     * 
@param cls 对象的类型
     * 
@param id ID值
     * 
@return 指定ID的对象
     
*/

    
public Object getObject(Class cls, String id)
    
{
        Object result 
= HibernateUtil.getCurrentSession().get(cls, id);
        
return result;
    }


    
/**
     * 删除对象信息
     * 
@param obj 被删除的对象
     
*/

    
public void deleteObject(Object obj)
    
{
        HibernateUtil.getCurrentSession().delete(obj);
    }

}

 

 

HibernateFilter
package cn.hxex.message.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class HibernateFilter implements Filter 
{
    
private static Log log = LogFactory.getLog(HibernateFilter.class);

    
public void init(FilterConfig filterConfig) throws ServletException {
        log.info(
"Servlet filter init, now opening/closing a Session for each request.");
    }


    
public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
            
throws IOException, ServletException 
    
{
        
// There is actually no explicit "opening" of a Session, the
        
// first call to HibernateUtil.beginTransaction() in control
        
// logic (e.g. use case controller/event handler, or even a
        
// DAO factory) will get a fresh Session.
        try 
        
{
            HibernateUtil.beginTransaction();
            
            request.setCharacterEncoding( 
"gb2312" );
            
            chain.doFilter(request, response);
            
// Commit any pending database transaction.
            HibernateUtil.commitTransaction();

        }
 
        
catch (ServletException ex) 
        
{
            log.debug(
"Rolling back the database transaction.");
            HibernateUtil.rollbackTransaction(); 
// Also closes the Session
            
// Just rollback and let others handle the exception, e.g. for display
            throw ex;
        }

        
catch (IOException ex) 
        
{
            log.debug(
"Rolling back the database transaction.");
            HibernateUtil.rollbackTransaction(); 
// Also closes the Session
            
// Just rollback and let others handle the exception, e.g. for display
            throw ex;
        }

        
finally 
        
{
            
// No matter what happens, close the Session.
            HibernateUtil.closeSession();
        }

    }


    
public void destroy() {}
}

 

HibernateUtil

package cn.hxex.message.util;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Interceptor;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;

public class HibernateUtil 
{

    
private static Log log = LogFactory.getLog(HibernateUtil.class);

    
private static final String INTERCEPTOR_CLASS = "hibernate.util.interceptor_class";

    
private static Configuration configuration;
    
private static SessionFactory sessionFactory;
    
private static ThreadLocal threadSession = new ThreadLocal();
    
private static ThreadLocal threadTransaction = new ThreadLocal();

    
private static boolean useThreadLocal = true;

    
static {
        
// Create the initial SessionFactory from the default configuration files
        try {

            
// Replace with Configuration() if you don't use annotations or JDK 5.0
            
//configuration = new AnnotationConfiguration();
            configuration = new Configuration();

            
// Read not only hibernate.properties, but also hibernate.cfg.xml
            configuration.configure();

            
// Assign a global, user-defined interceptor with no-arg constructor
            String interceptorName = configuration.getProperty(INTERCEPTOR_CLASS);
            
if (interceptorName != null{
                Class interceptorClass 
=
                        HibernateUtil.
class.getClassLoader().loadClass(interceptorName);
                Interceptor interceptor 
= (Interceptor)interceptorClass.newInstance();
                configuration.setInterceptor(interceptor);
            }


            
// Disable ThreadLocal Session/Transaction handling if CMT is used
            if (org.hibernate.transaction.CMTTransactionFactory.class.getName()
                 .equals( configuration.getProperty(Environment.TRANSACTION_STRATEGY) ) )
                useThreadLocal 
= false;

            
if (configuration.getProperty(Environment.SESSION_FACTORY_NAME) != null{
                
// Let Hibernate bind it to JNDI
                configuration.buildSessionFactory();
            }
 else {
                
// or use static variable handling
                sessionFactory = configuration.buildSessionFactory();
            }


        }
 catch (Throwable ex) {
            
// We have to catch Throwable, otherwise we will miss
            
// NoClassDefFoundError and other subclasses of Error
            log.error("Building SessionFactory failed.", ex);
            
throw new ExceptionInInitializerError(ex);
        }

    }


    
/**
     * Returns the original Hibernate configuration.
     *
     * 
@return Configuration
     
*/

    
public static Configuration getConfiguration() {
        
return configuration;
    }


    
/**
     * Returns the global SessionFactory.
     *
     * 
@return SessionFactory
     
*/

    
public static SessionFactory getSessionFactory() {
        SessionFactory sf 
= null;
        String sfName 
= configuration.getProperty(Environment.SESSION_FACTORY_NAME);
        
if ( sfName != null{
            log.debug(
"Looking up SessionFactory in JNDI.");
            
try {
                sf 
= (SessionFactory) new InitialContext().lookup(sfName);
            }
 catch (NamingException ex) {
                
throw new RuntimeException(ex);
            }

        }
 else {
            sf 
= sessionFactory;
        }

        
if (sf == null)
            
throw new IllegalStateException("SessionFactory not available.");
        
return sf;
    }


    
/**
     * Closes the current SessionFactory and releases all resources.
     * <p>
     * The only other method that can be called on HibernateUtil
     * after this one is rebuildSessionFactory(Configuration).
     
*/

    
public static void shutdown() {
        log.debug(
"Shutting down Hibernate.");
        
// Close caches and connection pools
        getSessionFactory().close();

        
// Clear static variables
        configuration = null;
        sessionFactory 
= null;

        
// Clear ThreadLocal variables
        threadSession.set(null);
        threadTransaction.set(
null);
    }



    
/**
     * Rebuild the SessionFactory with the static Configuration.
     * <p>
     * This method also closes the old SessionFactory before, if still open.
     * Note that this method should only be used with static SessionFactory
     * management, not with JNDI or any other external registry.
     
*/

     
public static void rebuildSessionFactory() {
        log.debug(
"Using current Configuration for rebuild.");
        rebuildSessionFactory(configuration);
     }


    
/**
     * Rebuild the SessionFactory with the given Hibernate Configuration.
     * <p>
     * HibernateUtil does not configure() the given Configuration object,
     * it directly calls buildSessionFactory(). This method also closes
     * the old SessionFactory before, if still open.
     *
     * 
@param cfg
     
*/

     
public static void rebuildSessionFactory(Configuration cfg) {
        log.debug(
"Rebuilding the SessionFactory from given Configuration.");
        
synchronized(sessionFactory) {
            
if (sessionFactory != null && !sessionFactory.isClosed())
                sessionFactory.close();
            
if (cfg.getProperty(Environment.SESSION_FACTORY_NAME) != null)
                cfg.buildSessionFactory();
            
else
                sessionFactory 
= cfg.buildSessionFactory();
            configuration 
= cfg;
        }

     }


    
/**
     * Retrieves the current Session local to the thread.
     * <p/>
     * If no Session is open, opens a new Session for the running thread.
     * If CMT is used, returns the Session bound to the current JTA
     * container transaction. Most other operations on this class will
     * then be no-ops or not supported, the container handles Session
     * and Transaction boundaries, ThreadLocals are not used.
     *
     * 
@return Session
     
*/

    
public static Session getCurrentSession() {
        
if (useThreadLocal) {
            Session s 
= (Session) threadSession.get();
            
if (s == null{
                log.debug(
"Opening new Session for this thread.");
                s 
= getSessionFactory().openSession();
                threadSession.set(s);
            }

            
return s;
        }
 else {
            
return getSessionFactory().getCurrentSession();
        }

    }


    
/**
     * Closes the Session local to the thread.
     * <p>
     * Is a no-op (with warning) if called in a CMT environment. Should be
     * used in non-managed environments with resource local transactions, or
     * with EJBs and bean-managed transactions.
     
*/

    
public static void closeSession() {
        
if (useThreadLocal) {
            Session s 
= (Session) threadSession.get();
            threadSession.set(
null);
            Transaction tx 
= (Transaction) threadTransaction.get();
            
if (tx != null && (!tx.wasCommitted() || !tx.wasRolledBack()) )
                
throw new IllegalStateException("Closing Session but Transaction still open!");
            
if (s != null && s.isOpen()) {
                log.debug(
"Closing Session of this thread.");
                s.close();
            }

        }
 else {
            log.warn(
"Using CMT/JTA, intercepted superfluous close call.");
        }

    }


    
/**
     * Start a new database transaction.
     * <p>
     * Is a no-op (with warning) if called in a CMT environment. Should be
     * used in non-managed environments with resource local transactions, or
     * with EJBs and bean-managed transactions. In both cases, it will either
     * start a new transaction or join the existing ThreadLocal or JTA
     * transaction.
     
*/

    
public static void beginTransaction() {
        
if (useThreadLocal) {
            Transaction tx 
= (Transaction) threadTransaction.get();
            
if (tx == null{
                log.debug(
"Starting new database transaction in this thread.");
                tx 
= getCurrentSession().beginTransaction();
                threadTransaction.set(tx);
            }

        }
 else {
            log.warn(
"Using CMT/JTA, intercepted superfluous tx begin call.");
        }

    }


    
/**
     * Commit the database transaction.
     * <p>
     * Is a no-op (with warning) if called in a CMT environment. Should be
     * used in non-managed environments with resource local transactions, or
     * with EJBs and bean-managed transactions. It will commit the
     * ThreadLocal or BMT/JTA transaction.
     
*/

    
public static void commitTransaction() {
        
if (useThreadLocal) {
            Transaction tx 
= (Transaction) threadTransaction.get();
            
try {
                
if ( tx != null && !tx.wasCommitted()
                                
&& !tx.wasRolledBack() ) {
                    log.debug(
"Committing database transaction of this thread.");
                    tx.commit();
                }

                threadTransaction.set(
null);
            }
 catch (RuntimeException ex) {
                log.error(ex);
                rollbackTransaction();
                
throw ex;
            }

        }
 else {
            log.warn(
"Using CMT/JTA, intercepted superfluous tx commit call.");
        }

    }


    
/**
     * Rollback the database transaction.
     * <p>
     * Is a no-op (with warning) if called in a CMT environment. Should be
     * used in non-managed environments with resource local transactions, or
     * with EJBs and bean-managed transactions. It will rollback the
     * resource local or BMT/JTA transaction.
     
*/

    
public static void rollbackTransaction() {
        
if (useThreadLocal) {
            Transaction tx 
= (Transaction) threadTransaction.get();
            
try {
                threadTransaction.set(
null);
                
if ( tx != null && !tx.wasCommitted() && !tx.wasRolledBack() ) {
                    log.debug(
"Tyring to rollback database transaction of this thread.");
                    tx.rollback();
                    log.debug(
"Database transaction rolled back.");
                }

            }
 catch (RuntimeException ex) {
                
throw new RuntimeException("Might swallow original cause, check ERROR log!", ex);
            }
 finally {
                closeSession();
            }

        }
 else {
            log.warn(
"Using CMT/JTA, intercepted superfluous tx rollback call.");
        }

    }


    
/**
     * Reconnects a Hibernate Session to the current Thread.
     * <p>
     * Unsupported in a CMT environment.
     *
     * 
@param session The Hibernate Session to be reconnected.
     
*/

    
public static void reconnect(Session session) {
        
if (useThreadLocal) {
            log.debug(
"Reconnecting Session to this thread.");
            session.reconnect();
            threadSession.set(session);
        }
 else {
            log.error(
"Using CMT/JTA, intercepted not supported reconnect call.");
        }

    }


    
/**
     * Disconnect and return Session from current Thread.
     *
     * 
@return Session the disconnected Session
     
*/

    
public static Session disconnectSession() {
        
if (useThreadLocal) {
            Transaction tx 
= (Transaction) threadTransaction.get();
            
if (tx != null && (!tx.wasCommitted() || !tx.wasRolledBack()) )
                
throw new IllegalStateException("Disconnecting Session but Transaction still open!");
            Session session 
= getCurrentSession();
            threadSession.set(
null);
            
if (session.isConnected() && session.isOpen()) {
                log.debug(
"Disconnecting Session from this thread.");
                session.disconnect();
            }

            
return session;
        }
 else {
            log.error(
"Using CMT/JTA, intercepted not supported disconnect call.");
            
return null;
        }

    }


    
/**
     * Register a Hibernate interceptor with the current SessionFactory.
     * <p>
     * Every Session opened is opened with this interceptor after
     * registration. Has no effect if the current Session of the
     * thread is already open, effective on next close()/getCurrentSession().
     * <p>
     * Attention: This method effectively restarts Hibernate. If you
     * need an interceptor active on static startup of HibernateUtil, set
     * the <tt>hibernateutil.interceptor</tt> system property to its
     * fully qualified class name.
     
*/

    
public static void registerInterceptorAndRebuild(Interceptor interceptor) {
        log.debug(
"Setting new global Hibernate interceptor and restarting.");
        configuration.setInterceptor(interceptor);
        rebuildSessionFactory();
    }


    
public static Interceptor getInterceptor() {
        
return configuration.getInterceptor();
    }

}

 

 

<?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="hibernate.connection.username">root</property>
    
<property name="hibernate.connection.url">
        jdbc:mysql://localhost:3306/guestmessagebook
    
</property>
    
<property name="hibernate.dialect">
        org.hibernate.dialect.MySQLDialect
    
</property>
    
<property name="myeclipse.connection.profile">mysql</property>
    
<property name="hibernate.connection.password">1234</property>
    
<property name="hibernate.connection.driver_class">
        com.mysql.jdbc.Driver
    
</property>
     
<property name="show_sql">true</property>
    
<mapping resource="cn/hxex/message/model/Message.hbm.xml" />
    
<mapping resource="cn/hxex/message/model/User.hbm.xml" />

</session-factory>

</hibernate-configuration>


MessageConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<config>
  
<bean id="userDao" 
        type
="cn.hxex.message.dao.hibernate.UserDAO"/>
  
<bean id="messageDao" 
        type
="cn.hxex.message.dao.hibernate.MessageDAO"/>    
</config>

 

index.jsp

 

<%@ page contentType="text/html;charset=gb2312" %> 
<%@ page isErrorPage="true" %>
<html>
<head>
<title>欢迎使用留言板系统!</title>
<meta http-equiv="content-type" content="text/html;charset=gb2312">
<link rel="stylesheet" href="css/common.css">
<script language="Javascript" src="pub/js/common.js"></script>
<script language="javascript">
  function checkValues(form)
{
    var checked
=[[form.name,"请输入用户名"],[form.password,"请输入密码"]];
    
if(!isRequired(checked)){
      
return false;
    }

    
return true;
  }

  function regist()
{
    window.location
="registinput.jsp";
  }

</script>
</head>
<body>
<center>
    
<h1>欢迎使用留言板系统!</h1>
    
<br>
    
<table width="500">
        
<form name="main" method="post" action="logon.jsp" onSubmit="return checkValues( this );">
        
<%
           
if(exception!=null){
         
%>
        
<tr>
            
<td colspan="2" class="warning">
               
<%=exception.getMessage() %>
            
</td>
        
</tr>
        
<%
            }

         
%>
         
<tr>
            
<td align="right">用户名:</td>
            
<td><input type="text" name="name"> *</td>
        
</tr>
        
<tr>
            
<td align="right">密码:</td>
            
<td><input type="password" name="password"> *</td>
        
</tr>
        
<tr>
            
<td align="left">&nbsp;&nbsp;</td>
            
<td align="left"><input type="submit" name="login" value="登录">
            
<input type="button" name="register" value="注册" onClick="regist();"></td>
        
</tr>
        
<tr>
            
<td align="right" colspan="2">
                
<img height="200" src="img/welcome.gif">            </td>
        
</tr>
        
</form>
    
</table>
</center>
</body>
</html>

 

logon.jsp

<%@ page contentType="text/html;charset=gb2312" %>
<%@ page import="cn.hxex.message.dao.IUserDAO,
                cn.hxex.message.util.DaoFactory,
                cn.hxex.message.model.User,
                cn.hxex.message.exception.MessageDAOException,
                cn.hxex.message.constants.Constants
" %>
<jsp:useBean id="user" scope="request" class="cn.hxex.message.model.User"></jsp:useBean>
<jsp:setProperty name="user" property="*"/>
<%
    IUserDAO userDAO 
= (IUserDAO)DaoFactory.getDao( "userDao" );
    User u 
= userDAO.getUser( user.getName() );
    
if( u==null || !u.getPassword().equals( user.getPassword() ) )
    {
        throw 
new MessageDAOException( "用户不存在或者密码错误!" );
    }
    session.setAttribute( Constants.SESSION_USER, u.getId() );
    
    response.sendRedirect( 
"message.jsp" );
%>

 

message.jsp

<%@ page contentType="text/html;charset=gb2312" %>
<%@ page import="cn.hxex.message.dao.IMessageDAO,
                cn.hxex.message.util.DaoFactory,
                cn.hxex.message.model.Message,
                cn.hxex.message.constants.Constants,
                java.util.List
" %>

<html>
<head>
<title>留言列表</title>
<meta http-equiv="content-type" content="text/html;charset=gb2312">
<link rel="stylesheet" href="css/common.css">
<script language="Javascript" src="pub/js/common.js"></script>
<script language="javascript">
  
function checkValues(form){
    var checked
=[[form.title,"请输入留言标题"],[form.content,"请输入留言内容"]];
    
if(!isRequired(checked)){
      return 
false;
    }
    return 
true;
  }
</script>
</head>
<body>
<center>
<h1>留言列表</h1>
<table width="80%" border="1">

    
<tr>
      
<td align="center">标题</td>
      
<td align="center">发布人</td>
      
<td align="center">内容</td>
      
<td align="center">操作</td>
    
</tr>
    
<%
     
String id=(String)session.getAttribute(Constants.SESSION_USER);
     IMessageDAO msgDao
=(IMessageDAO)DaoFactory.getDao("messageDao");
     List msgs
=msgDao.getMessages();
     
for(int i=0;i<msgs.size();i++)
     {
        Message msg
=(Message)msgs.get(i);
     
 
%>
    
<tr>
        
<td width="120" align="left"><%=msg.getTitle() %></td>
        
<td width="60" align="left"><%=msg.getUser().getName() %></td>
        
<td width="250" align="left"><%=msg.getContent() %></td>
        
<td width="80" align="center">
        
<%
           
if(msg.getUser().getId().equals(id)){
         
%>
        
<href="messagedel.jsp?id=<%=msg.getId()%>" >删除</a>
                
<href="messageupdateinput.jsp?id=<%=msg.getId() %>" >修改</a>
        
<%
            }
            
else{
              out.println(
"&nbsp;");
            }
         
%>
         
</td>
    
</tr>
    
<%
        }
     
%>
</table>

<hr>

<table width="80%">
    
<form name="main" method="post" action="messagesave.jsp" onSubmit="return checkValues( this );">
    
<tr>
        
<td>标题:</td>
        
<td><input type="text" name="title" size="40" maxlength="32">*</td>
        
<td rowspan="3">
            
<img src="img/content.gif" width="120">
        
</td>
    
</tr>
    
<tr>
        
<td>内容:</td>
        
<td><textarea name="content" cols="40" rows="10"></textarea>*</td>
    
</tr>
    
<tr>
        
<td align="center" colspan="2">
            
<input type="submit" name="regist" value="发布">&nbsp;&nbsp;
            
<input type="reset" name="reset" value="重写">
        
</td>
    
</tr>
    
</form>
</table>
</center>
</body>
</html>

messagedel.jsp

 

<%@ page contentType="text/html;charset=gb2312" %>
<%@ page import="cn.hxex.message.dao.IUserDAO,
                cn.hxex.message.dao.IMessageDAO,
                cn.hxex.message.util.DaoFactory,
                cn.hxex.message.model.User,
                cn.hxex.message.model.Message,
                cn.hxex.message.constants.Constants,
                cn.hxex.message.exception.MessageDAOException,
                java.util.List
" %>
<%
   
String id=request.getParameter("id");
   
String userid=(String)session.getAttribute(Constants.SESSION_USER);
   IMessageDAO msgDao
=(IMessageDAO)DaoFactory.getDao("messageDao");
   msgDao.deleteMessage(id,userid);
   response.sendRedirect(
"message.jsp");
%>

messagesave.jsp

<%@ page contentType="text/html;charset=gb2312" %>
<%@ page import="cn.hxex.message.dao.IUserDAO,
                cn.hxex.message.dao.IMessageDAO,
                cn.hxex.message.util.DaoFactory,
                cn.hxex.message.model.User,
                cn.hxex.message.model.Message,
                cn.hxex.message.constants.Constants,
                java.util.List
" %>

<jsp:useBean id="msg" scope="request" class="cn.hxex.message.model.Message">
</jsp:useBean>
<jsp:setProperty name="msg" property="*"/>

<%
  
String userId=(String)session.getAttribute(Constants.SESSION_USER);
  IUserDAO userDao
=(IUserDAO)DaoFactory.getDao("userDao");
  User u
=userDao.getUserById(userId);
  IMessageDAO msgDao
=(IMessageDAO)DaoFactory.getDao("messageDao");
  msg.setUser(u);
  msgDao.saveMessage(msg);
  response.sendRedirect(
"message.jsp");
%>


messageupdate.jsp

<%@ page contentType="text/html;charset=gb2312" %>
<%@ page import="cn.hxex.message.dao.IUserDAO,
                cn.hxex.message.dao.IMessageDAO,
                cn.hxex.message.util.DaoFactory,
                cn.hxex.message.model.User,
                cn.hxex.message.model.Message,
                cn.hxex.message.constants.Constants,
                cn.hxex.message.exception.MessageDAOException,
                java.util.List
" %>
<jsp:useBean id="msg" scope="request" class="cn.hxex.message.model.Message"></jsp:useBean>
<jsp:setProperty property="*" name="msg"/>
<%
   
String userId=(String)session.getAttribute(Constants.SESSION_USER);
   IUserDAO userDao
=(IUserDAO)DaoFactory.getDao("userDao");
   User u
=userDao.getUserById(userId);
   IMessageDAO msgDao
=(IMessageDAO)DaoFactory.getDao("messageDao");
   msg.setUser(u);
   msgDao.updateMessage(msg);
   response.sendRedirect(
"message.jsp");
%>


messageupdateinput.jsp

<%@ page contentType="text/html;charset=gb2312" %>
<%@ page import="cn.hxex.message.dao.IUserDAO,
                cn.hxex.message.dao.IMessageDAO,
                cn.hxex.message.util.DaoFactory,
                cn.hxex.message.model.User,
                cn.hxex.message.model.Message,
                cn.hxex.message.constants.Constants,
                cn.hxex.message.exception.MessageDAOException,
                java.util.List
" %>
<jsp:include flush="true" page="pub/jsp/authority.jsp"></jsp:include>
<%
    
String id=(String)request.getParameter("id");
    IMessageDAO msgDao
=(IMessageDAO)DaoFactory.getDao("messageDao");
    Message msg
=(Message)msgDao.getMessage(id);
    
if(msg==null){
      throw 
new MessageDAOException("找不到需要修改的留言");
    }
 
%>
<html>
<head>
<title>修改留言</title>
<meta http-equiv="content-type" content="text/html;charset=gb2312">
<link rel="stylesheet" href="css/common.css">
<script language="Javascript" src="pub/js/common.js"></script>
<script language="javascript">
  
function checkValues(form){
    
var checked=[[form.title,"请输入留言标题"],[form.content,"请输入留言内容"]];
    
if(!isRequired(checked)){
      
return false;
    }

    
return true;
  }

  
function message(){
    window.location
="message.jsp";
  }

</script>
</head>
<body>
<center>

<h1>修改留言</h1>
<table width="80%">
    
<form name="main" method="post" action="messageupdate.jsp" onsubmit="return checkValues( this );">
    
<tr>
        
<td>标题:</td>
        
<td><input type="text" name="title" size="50" maxlength="32" value="<%=msg.getTitle() %>">*</td>
    
</tr>
    
<tr>
        
<td>内容:</td>
        
<td><textarea name="content" cols="50"><%=msg.getContent() %></textarea>*</td>
    
</tr>
    
<tr>
        
<td align="center" colspan="2">
            
<input type="submit" name="save" value="保存">&nbsp;&nbsp;
            
<input type="reset" name="reset" value="重填">&nbsp;&nbsp;
            
<input type="button" name="return" value="取消" onclick="message();">
            
<input type="hidden" name="id" value="<%=msg.getId() %>">
        
</td>
    
</tr>
    
<tr>
        
<td align="center" colspan="2">
            
&nbsp;<br>
            
<img src="img/update.gif" width="150">
        
</td>
    
</tr>
    
</form>
</table>

</center>
</body>
</html>

regist.jsp


<%@ page contentType="text/html;charset=gb2312" %>
<%@ page import="cn.hxex.message.dao.IUserDAO,
                cn.hxex.message.util.DaoFactory,
                cn.hxex.message.model.User,
                cn.hxex.message.constants.Constants
" %>
                
<jsp:useBean id="user" scope="request" class="cn.hxex.message.model.User">
</jsp:useBean>
<jsp:setProperty property="*" name="user"/>
<%
    System.out.println(user);
    IUserDAO userDao
=(IUserDAO)DaoFactory.getDao("userDao");
    userDao.saveUser(user);
   
    session.setAttribute(Constants.SESSION_USER,user.getId());
    response.sendRedirect(
"message.jsp");
 
%>

 

registinput.jsp

<%@ page contentType="text/html;charset=gb2312" %>
<html>
<head>
<title>请输入注册信息!</title>
<meta http-equiv="content-type" content="text/html;charset=gb2312">
<link rel="stylesheet" href="css/common.css">
<script language="Javascript" src="pub/js/common.js"></script>

</head>
<script language="javascript">
  
function checkValues(form){
    
var checks=[[form.name,"请输入用户名"],[form.password,"请输入密码"],[form.repassword,"请输入确认密码"]];
    
if(!isRequired(checks)){
      
return false;
    }

    
if(form.password.value!=form.repassword.value){
      alert(
"密码输入不一致,请重新输入");
      form.password.value
="";
      form.repassword.value
="";
      form.password.focus();
      
return false;
    }

    
return true;
  }

  
function logon(){
    window.location
="index.jsp";
  }

</script>
<body>
<center>
    
<h1>用户注册</h1>
    
<br>
    
<table width="300">
        
<tr>
            
<td colspan="2" align="center" class="warnning">&nbsp;&nbsp;&nbsp;请输入注册信息!</td>
        
</tr>
        
<form name="main" method="post" action="regist.jsp" onSubmit="return checkValues( this );">
        
<tr>
            
<td align="right">用户名:</td>
            
<td><input type="text" name="name"> *</td>
        
</tr>
        
<tr>
            
<td align="right">密码:</td>
            
<td><input type="password" name="password"> *</td>
        
</tr>
        
<tr>
            
<td align="right">确认密码:</td>
            
<td><input type="password" name="repassword"> *</td>
        
</tr>
        
<tr>
            
<td align="center" colspan="2">
                
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" name="regist" value="注册"> 
                
<input type="reset" name="reset" value="重填">
                
<input type="button" name="Logon" value="返回" onClick="logon();">
            
</td>
        
</tr>
        
<tr>
            
<td align="center" colspan="2">
                
&nbsp;<p><p>
                
<img src="img/register.gif" height="120">
            
</td>
        
</tr>
        
</form>
    
</table>
</center>
</body>
</html>

 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  
   
<filter>
        
<filter-name>HibernateFilter</filter-name>
        
<filter-class>cn.hxex.message.util.HibernateFilter</filter-class>
    
</filter>

    
<filter-mapping>
        
<filter-name>HibernateFilter</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>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>
  
<error-page>
    
<exception-type>
       cn.hxex.message.exception.MessageDAOException
    
</exception-type>
    
<location>/error/daoerror.jsp</location>
  
</error-page>
  
<error-page>
        
<error-code>404</error-code>
        
<location>/index.jsp</location>
    
</error-page>
    
<error-page>
        
<exception-type>cn.hxex.message.exception.MessageAuthorityException</exception-type>
        
<location>/index.jsp</location>
    
</error-page>
</web-app>

 

common.js

function isRequired( checked )
{
    
forvar i=0; i<checked.length; i++ )
    
{
        
var input = checked[i][0];
        
if( input.value==null || input.value.length==0 )
        
{
            alert( checked[i][
1] );
            input.focus();
            
return false;
        }

    }

    
return true;
}

 

authority.jsp

<%@ page contentType="text/html;charset=gb2312" %>
<%@page import="cn.hxex.message.constants.Constants,
                cn.hxex.message.exception.MessageAuthorityException" %>
<%
    
String id = (String)session.getAttribute(Constants.SESSION_USER);
    
if( id==null || id.length()==0 )
    {
        throw 
new MessageAuthorityException( "你没有登录,请重新登录!" );
    }
%>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值