Struts2+spring+hibernate框架

SSH在J2EE开发中有个广泛的应用,下面就是我在具体代码,请大家参考,如果有错误也希望大家能指出:

1.BaseDao:数据库原子方法的接口类,列出基本方法,大家可以完善:

public interface BaseDAO extends Serializable{

public Serializable save(BaseDomain domain);  

public void update(BaseDomain domain);

public void delete(BaseDomain domain);    

public BaseDomain findByID(String entityName, Serializable id);

public BaseDomain get(Class claz,Serializable id) throws Exception;

public int getRecordCountByHqlQuery(String hql) ; 

public List findColsByHqlQuerySupportPaging(final String hql, final int start, final int reCount);  

}

2.BaseDaoImpl:具体实现类

public class BaseDAOImpl extends HibernateDaoSupport implements BaseDAO {

    public Serializable save(BaseDomain domain) {
        return getHibernateTemplate().save(domain);
    }

    public void update(BaseDomain domain) {
        getHibernateTemplate().update(domain);
    }

    public void delete(BaseDomain domain) {
        getHibernateTemplate().delete(domain);
    }

    public BaseDomain findByID(String entityName, Serializable id) {
        return (BaseDomain) getHibernateTemplate().get(entityName, id);
    }

    public List findColsByHqlQuerySupportPaging(final String hql,final int start, final int reCount) {

         List resultList = getHibernateTemplate().executeFind(new HibernateCallback(){

         public Object doInHibernate(Session session)  
                    throws HibernateException, SQLException {

                 Query query = session.createQuery(hql);  
                 query.setFirstResult(start*reCount);  
                 query.setMaxResults(reCount);                     
                  return query.list();  

                }                 
        });  
       return resultList;  }

     public int getRecordCountByHqlQuery(String hql) {  
        int recordCount = Integer.parseInt(String.valueOf(getHibernateTemplate().find(hql).get(0)));
        return recordCount;       
     }

     public BaseDomain get(Class claz, Serializable id) throws Exception {
          return (BaseDomain) getHibernateTemplate().get(claz, id);
    }

}

3.BaseService:业务层的接口方法。

public interface BaseService{}

4.BaseServiceImpl:业务层具体实现类,注入baseDao,代码如下:

public class BaseServiceImpl implements BaseService {

    protected BaseDAO baseDao;
    public BaseDAO getBaseDao() {
        return baseDao;
    }

    public void setBaseDao(BaseDAO baseDao) {
        this.baseDao = baseDao;
    }

}

5.BaseDomain:所有pojo的基类

public abstract class BaseDomain  implements java.io.Serializable{ }

6.BaseAction:Struts2的基类,所有action都继承它,提供了request,reponse,session等属性。

public class BaseAction extends ActionSupport implements ServletRequestAware,ServletResponseAware,SessionAware {
    protected HttpServletRequest request = null;
    protected HttpServletResponse response = null;
    protected Map session;   
    protected String message;

    public void sendJsonString(String json){
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        try {
            PrintWriter out = response.getWriter();
            out.print(json);
            out.flush();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
    }   

    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }

    public void setSession(Map session) {
        this.session = session;
    }

    public void setServletResponse(HttpServletResponse response) {
        // TODO Auto-generated method stub
        this.response = response;
    }

    public int getCurrentPage() {
        int currentPage = 0;
        Enumeration paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String name = (String) paramNames.nextElement();
            if (name != null && name.startsWith("d-") && name.endsWith("-p")) {
                String pageValue = request.getParameter(name);
                if (pageValue != null) {
                    currentPage = Integer.parseInt(pageValue) - 1;
                }
            }
        }
        return currentPage;
    } //displaytag翻页处理,得到当前页码

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

7.applicationContext.xml:spring配置文件类:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="  
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
            </list>
        </property>
    </bean>
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName">
            <value>${driver}</value>
        </property>
        <property name="url">
            <value>${url}</value>
        </property>
        <property name="username">
            <value>${username}</value>
        </property>
        <property name="password">
            <value>${password}</value>
        </property>
    </bean>
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${dialect}</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
        <property name="mappingDirectoryLocations"> 
            <list> 
                <value>classpath*:/com/telenavsoftware/member/domain/xml</value> 
            </list> 
        </property>
    </bean>
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <tx:advice id="txAdvice" transaction-manager="transactionManager">  
        <tx:attributes>  
             <tx:method name="save*" propagation="REQUIRED" /> 
             <tx:method name="delete*" propagation="REQUIRED" /> 
             <tx:method name="update*" propagation="REQUIRED" />           
                <tx:method name="find*" propagation="REQUIRED" read-only="true"/>
             <tx:method name="*" read-only="true" /> 
        </tx:attributes>  
    </tx:advice>  
    <aop:config proxy-target-class="true">  
       <aop:advisor pointcut="execution(* com.yourcompany.*.service.impl.*.*(..))" advice-ref="txAdvice" />  
    </aop:config>
       <bean id="baseDao" class="com.telenavsoftware.framework.dao.Impl.BaseDAOImpl">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <bean id="baseService" class="com.telenavsoftware.framework.service.impl.BaseServiceImpl">
        <property name="baseDao" ref="baseDao"></property>
    </bean>

    <bean id="xxxService" class="com.yourcompany.service.impl.UserServiceImpl" parent="baseService"></bean>
    <bean id="xxxAction" class="com.yourcompany.action.UserAction" lazy-init="true">
        <property name="xxxService" ref="xxxService"></property>
    </bean>
    </beans>

8.struts.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <include file="struts-default.xml"/>
<constant name="struts.serve.static.browserCache" value="true"/>

    <package name="member" extends="struts-default" namespace="/member">
         <interceptors>  
            <interceptor name="loginInterceptor" class="com.yourcompany.interceptor.LoginInterceptor"></interceptor>
            <interceptor name="permissionInterceptor" class="com.yourcompany.interceptor.PermissionInterceptor"></interceptor>
            <interceptor-stack name="loginDefaultStack">  
                <interceptor-ref name="loginInterceptor"></interceptor-ref>
                <interceptor-ref name="defaultStack"></interceptor-ref>  
            </interceptor-stack> 
        </interceptors>
        <default-interceptor-ref name="loginDefaultStack"></default-interceptor-ref>
        <action name="*User" class="userAction" method="{1}">
            <result>/member/user/{1}_user.jsp</result>
            <result name="input">/member/user/{1}_user.jsp</result>
            <result name="delete" type="redirect">queryUser.action</result>
        </action>

        <action name="*" class="userAction">
            <result>/member/{1}.jsp</result>
            <interceptor-ref name="defaultStack"></interceptor-ref> 
        </action>
    </package>
</struts>

9.struts.properties:

struts.custom.i18n.resources=applicationMessages  //资源文件名称
struts.locale=zh_CN //默认区域
struts.i18n.encoding=UTF-8  //UTF-8编码
struts.objectFactory=spring  //将struts的所有action交给spring去控制
struts.devMode=false  //是否为debug模式,如果为true,打印相应debug信息

10.jdbc.properties:

driver=com.mysql.jdbc.Driver
dialect=org.hibernate.dialect.MySQLDialect
url=jdbc:mysql://localhost:3306/member?&Unicode=true&characterEncoding=UTF-8
username=root
password=12345

11.web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <display-name>Demo</display-name>
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:log4j.properties</param-value>
    </context-param>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>   
    <filter>
        <filter-name>hibernateFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>        //防止session的servlet层关闭    
    </filter>

    <filter-mapping>
        <filter-name>hibernateFilter</filter-name>
        <url-pattern>*.action</url-pattern>
    </filter-mapping>
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>

    <session-config>
        <session-timeout>10</session-timeout>
    </session-config>
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
</web-app>

  • 0
    点赞
  • 1
    评论
  • 0
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

评论 1 您还未登录,请先 登录 后发表或查看评论
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页

打赏作者

joy00112233

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值