struts+hibernate(dao)+filter的例子

表﹕company 

id 公司ID 
company_name 公司名稱 

配置就不說了﹐ 

po:company.java 

java代码: 

public class Company { 
        private String id; 
        private String companyname; 
        
        public String getId(){ 
                return id; 
        } 
        public String getCompanyname(){ 
                return companyname; 
        } 
        
        public void setId(String id){ 
                this.id=id; 
        } 
        public void setCompanyname(String companyname){ 
                this.companyname=companyname; 
        } 
}



company持久類對應的映射文件﹕ 
company.hbm.xml 

java代码: 

<?xml version="1.0"?> 

<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 2.0//EN" 
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"> 

<hibernate-mapping> 
    <class name="com.foxconn.hibernate.po.Company" table="company" dynamic-update="false"> 
        <id name="id" column="id" type="string" unsaved-value="any" > 
            <generator class="assigned"> 
            </generator> 
        </id> 
        <property name="companyname" type="string" update="true" insert="true" column="company_name"/> 
    </class> 
</hibernate-mapping>



配置文件hibernate.cfg.xml 

java代码: 

<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration D 

TD//EN" "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd"> 

<hibernate-configuration> 

<session-factory> 

<property name="connection.datasource">java:comp/env/jdbc/fox221</property> 

<property name="show_sql">false</property> 

<property name="dialect">net.sf.hibernate.dialect.OracleDialect</property> 

<property name="jdbc.fetch_size">50</property> 

<property name="jdbc.batch_size">30</property> 

<!-- Mapping files --> 

<mapping resource="/hbm/Company.hbm.xml"/> 

</session-factory> 

</hibernate-configuration>



提供session的类HebernateSessionFactory(利用Thread管理session) 

java代码: 

public class HibernateSessionFactory { 
    public static final ThreadLocal session = new ThreadLocal(); 
    private static SessionFactory sessionFactory; 

     static { 
        try { 
            sessionFactory = 
                    new Configuration().configure().buildSessionFactory(); 
        } catch (HibernateException ex) { 
            throw new RuntimeException( 
                    "Exception building SessionFactory: " + ex.getMessage(),ex); 
        } 
    } 

    public static Session currentSession() throws HibernateException{ 
                Session s = (Session) session.get(); 
                if (s == null) { 
                    s =  sessionFactory.openSession(); 
                    session.set(s); 
                } 
                return s; 
    } 
    public static void closeSession() throws HibernateException{ 
        Session s = (Session) session.get(); 
        session.set(null); 
        if (s != null) s.close(); 
    } 
    
}



封装CRUD操作的类(我觉的此类应该设置为abstract类) 

java代码: 

public class HibernateUtil { 
    public static void add( Object object )throws HibernateException{        Session s = HibernateSessionFactory.currentSession(); 
        s.save( object ); 
        s.flush(); 
        s.beginTransaction().commit(); 
    } 
    public static void update( Object object ) throws HibernateException { 
        Session s = HibernateSessionFactory.currentSession(); 
        s.beginTransaction(); 
        s.saveOrUpdate( object ); 
        s.flush(); 
    } 
    public static void remove(Class clazz, String id) throwsHibernateException { 
        Session s = HibernateSessionFactory.currentSession(); 
        s.beginTransaction(); 
        Object object = s.load(clazz, id); 
        s.delete( object ); 
        s.flush(); 
    } 
    public static Object findById( Class clazz, String id ) throwsHibernateException { 
        Object obj = null; 
        Session s = HibernateSessionFactory.currentSession(); 
        obj = s.load( clazz, id ); 
        s.flush(); 
        return obj; 
    } 
}



在filter中关闭session,这个filter还可以用于字符集转换. 
HibernateFilter.java 

java代码: 

public class HibernateFilter implements Filter { 
   private String encode = "big5"; 
    
    public void init(FilterConfig config) { 
        this.encode = config.getInitParameter("encode"); 
    } 

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { 
        try{ 
            request.setCharacterEncoding(this.encode); 
            response.setContentType("text/html;charset="+encode); 
            chain.doFilter(request, response); 
        } 
        catch(Exception e){ 
            if(!(e instanceof java.net.SocketException)){ 
                if(request instanceof HttpServletRequest) 
                    Logger.getLogger(this.getClass()).error("error request uri:"+((HttpServletRequest)request).getRequestURI()); 
                Logger.getLogger(this.getClass()).error(e); 
            } 
        }finally{ 
                try{ 
                        HibernateSessionFactory.closeSession(); 
                }catch(Exception ex){ 
                        System.out.println("Error in closing session"); 
                }        
        } 
    } 

    public void destroy() { 
    } 
}


以上是hibernate相关部分.

companyDAO.java 是个接口. 

java代码: 

public interface CompanyDAO { 
        public void addCompany(Company company) throws HibernateException; 
}



工厂类HibernateDAOFactory.java 

java代码: 

public class HibernateDAOFactory implements DAOFactory{ 
    public static Object getInstance(String subClassName) throws 
        ClassNotFoundException, 
        InstantiationException, 
        IllegalAccessException{ 
        return (Class.forName(subClassName).newInstance()); 
    } 
}



DAO的实现类CompanyDAOImpl 

java代码: 

public class CompanyDAOImpl implements CompanyDAO{ 

        public void addCompany(Company company) throws HibernateException{ 
                                HibernateUtil.add(company); 
        } 

}



struts的action类只负责控制转发CompanyAction.java 

java代码: 

public class CompanyControl extends DispatchAction{ 

        public ActionForward saveCompany(ActionMapping mapping,ActionForm form ,HttpServletRequest request,HttpServletResponse response) throws Exception{ 
            HttpSession session = request.getSession(); 
            
            String id=request.getParameter("id"); 
            String name=request.getParameter("name"); 
            
            Company company=new Company(); 
            company.setId(id); 
            company.setCompanyname(name); 
            
            CompanyDAO companyDAO=(CompanyDAO)HibernateDAOFactory.getInstance("CompanyDAOImpl"); 
            companyDAO.addCompany(company); 
            
            return mapping.findForward("success"); 
    }        
}

下面是相关的两个页面.index.jsp和保存后成功页面success.jsp 

index.jsp 

<%@ page contentType="text/html; charset=Big5" %> 
<%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %> 
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %> 
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> 
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %> 

<html:html> 
<head> 
<link href="<%= request.getContextPath() %>/style/SelfCss.css" rel="stylesheet" type="text/css"> 
</head> 
<body> 
<html:form action="company.do?action=saveCompany"> 
<table> 
<tr> 
<td>Company ID:</td> 
<td><html:text property="id" /></td> 
</tr> 
<tr> 
<td>Company Name:</td> 
<td><html:text property="name" /></td> 
</tr> 
<tr> 
<td><html:submit value="submit" /></td> 
<td><html:reset value="reset"/></td> 
</tr> 
</table> 
</html:form> 
</body> 
</html:html> 

success.jsp 此画面用来输出成功插入的信息! 

<html:html> 
<body> 
Successful!!! 
</body> 
</html:html>

posted on 2017-07-10 11:04  alex5211314  阅读(198)  评论(0)    收藏  举报

导航