1. Struts2(struts-2.2.3.1)

1.1 加入struts2的jar包

     解压缩"struts2-blank"空项目,lib下的jar包全部拷贝。

1.2 web.xml加入struts2的过滤器

 <filter>
  <filter-name>struts2</filter-name>
  <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
   </filter>
  <filter-mapping>
  <filter-name>struts2</filter-name>
 <url-pattern>/*</url-pattern>
 </filter-mapping>

1.3 添加struts.xml

     解压缩"struts2-blank"空项目,拷贝其中的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.enable.DynamicMethodInvocation" value="true" />
    <constant name="struts.devMode" value="true" />
   <constant name="struts.objectFactory" value="org.apache.struts2.spring.StrutsSpringObjectFactory" />

    <package name="default" namespace="/" extends="struts-default">
        <default-action-ref name="index" />
        <global-results>
            <result name="error">/error.jsp</result>
        </global-results>
        <global-exception-mappings>
            <exception-mapping exception="java.lang.Exception" result="error"/>
        </global-exception-mappings>
        <action name="index">
            <result>/index.jsp</result>
        </action>
    </package>

 <package name="user" namespace="/user" extends="struts-default">
  <action name="userEdit_*" method="{1}" class="com.sample.action.UserEditAction">
            <result name="edit">/userEdit.jsp</result>
            <result name="list" type="redirect">/user/userList_init</result>
        </action>
        <action name="userList_*" method="{1}" class="com.sample.action.UserListAction">
            <result name="display">/userList.jsp</result>
        </action>
 </package>
</struts>

 

2. Hibernate(hibernate-3.3.2 hibernate-annotations-3.4.0)

 2.1 拷贝jar包(参照我的标题为SSH2 JAR的随笔)

 2.2 创建hibernate.cfg.xml文件

<?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">

<hibernate-configuration>

    <session-factory>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/spring</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  <!-- Database connection settings
  <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:invigilate</property>
        <property name="connection.username">invigilate</property>
        <property name="connection.password">invigilate</property>
        <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
        -->
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        <!-- Echo all formatted SQL to stdout -->
        <property name="hibernate.format_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>

        <!--<mapping resource="com/sample/hibernate/model/Student.hbm.xml"/>
        <mapping class="com.sample.hibernate.model.Teacher"/>
        -->
        <mapping class="com.sample.model.User"/>
    </session-factory>
</hibernate-configuration>

 2.3 最好把日志配好(jar包在2.1的时候已经导入)

    log4j.properties:

log4j.rootLogger=debug,stdout,info,warn,error

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p %F:%L - %m%n
log4j.appender.stdout.encoding=UTF-8
 
log4j.logger.info=info
log4j.appender.info=org.apache.log4j.DailyRollingFileAppender
log4j.appender.info.layout=org.apache.log4j.PatternLayout
log4j.appender.info.layout.ConversionPattern=[%p] [%d{yyyy-MM-dd HH:mm:ss}]  [ Class = %C | Method = %M | Line = %L ] | %m |%n  
log4j.appender.info.datePattern='.'yyyy-MM-dd
log4j.appender.info.Threshold=INFO
log4j.appender.info.append=true
log4j.appender.info.Encoding=UTF-8
log4j.appender.info.File=info.log

log4j.logger.debug=debug
log4j.appender.debug=org.apache.log4j.DailyRollingFileAppender
log4j.appender.debug.layout=org.apache.log4j.PatternLayout
log4j.appender.debug.layout.ConversionPattern=[%p] [%d{yyyy-MM-dd HH:mm:ss}]  [ Class = %C | Method = %M | Line = %L ] | %m |%n  
log4j.appender.debug.datePattern='.'yyyy-MM-dd
log4j.appender.debug.Threshold=DEBUG
log4j.appender.debug.append=true
log4j.appender.debug.Encoding=UTF-8
log4j.appender.debug.File=debug.log
 
log4j.logger.warn=warn
log4j.appender.warn=org.apache.log4j.DailyRollingFileAppender
log4j.appender.warn.layout=org.apache.log4j.PatternLayout
log4j.appender.warn.layout.ConversionPattern=[%p] [%d{yyyy-MM-dd HH:mm:ss}]  [ Class = %C | Method = %M | Line = %L ] | %m |%n  
log4j.appender.warn.datePattern='.'yyyy-MM-dd
log4j.appender.warn.Threshold=WARN
log4j.appender.warn.append=true
log4j.appender.warn.Encoding=UTF-8
log4j.appender.warn.File=warn.log
 
log4j.logger.error=error
log4j.appender.error=org.apache.log4j.DailyRollingFileAppender
log4j.appender.error.layout=org.apache.log4j.PatternLayout
log4j.appender.error.layout.ConversionPattern=[%p] [%d{yyyy-MM-dd HH:mm:ss}]  [ Class = %C | Method = %M | Line = %L ] | %m |%n  
log4j.appender.error.datePattern='.'yyyy-MM-dd
log4j.appender.error.Threshold=ERROR
log4j.appender.error.append=true
log4j.appender.error.Encoding=UTF-8
log4j.appender.error.File=error.log

 

 2.4 到这里为止struts2, hibernate的构筑完了, 开始引入Spring

 3 导入Jar包

 3.1 spring-framework-3.0.5.RELEASE\dist目录下全部的Jar包

 3.2 aopalliance-1.0.jar,com.springsource.net.sf.cglib-2.2.0.jar

       com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar

   commons-dbcp-1.3.jar, commons-pool-1.5.6.jar, commons-logging-1.1.1.jar

4 添加修改配置文件

 4.1 修改web.xml文件,加入如下语句:

<context-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>/WEB-INF/classes/applicationContext-*.xml,classpath*:applicationContext-*.xml</param-value>
 </context-param>
<listener>
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

 

4.2 修改struts.xml文件,加入如下语句:

<constant name="struts.objectFactory" value="org.apache.struts2.spring.StrutsSpringObjectFactory" />

 

4.3 添加applicationConext.xml

<?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" xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-3.0.xsd
   http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

 <context:annotation-config />
 <context:component-scan base-package="com.sample" />

 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
  destroy-method="close">
  <property name="driverClassName" value="${jdbc.driverClassName}" />
  <property name="url" value="${jdbc.url}" />
  <property name="username" value="${jdbc.username}" />
  <property name="password" value="${jdbc.password}" />

 </bean>

 <bean id="sessionFactory"
  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <!-- xm方式 -->
  <!--
   <property name="mappingResources"> <list>
   <value>product.hbm.xml</value> </list> </property>
  -->
  <!-- annotated方式

 <property name="annotatedClasses">
   <list>
    <value>com.sample.model.User</value>
   </list>
  </property>

 -->
  <!-- 包读取方式 -->
  <property name="packagesToScan">
   <list>
    <value>com.sample.model</value>
   </list>
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
    <prop key="hibernate.show_sql">true</prop>
   </props>
   <!--
    <value> hibernate.dialect=org.hibernate.dialect.MySQLDialect
    </value>
   -->
  </property>
 </bean>

<context:property-placeholder location="jdbc.properties" />
<!--
 <bean id="propertyConfigurer"
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="locations" value="jdbc.properties" />
 </bean>
-->
</beans>

 

4.4 修改Bean

类型上加注解:[@Component("userManager")]

成员变量的Set上面加注解:@Resource(name="userDao")

 

5 加入spring的事务管理(XML方式)

 5.1 在spring配置文件中加入HibernateTransactionManager

<bean id="transactionManager"
  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory" />
 </bean>

 

 5.2 在spring配置文件中加入advice

<tx:advice id="txAdvisor" transaction-manager="transactionManager">
  <tx:attributes>
   <tx:method name="get*" read-only="true" />
   <tx:method name="*" />
  </tx:attributes>
 </tx:advice>

 

 5.3 在spring配置文件中加入aopconfig

<aop:config>
  <aop:pointcut expression="execution(public * com.sample.service..*.*(..))"
   id="userServicePointcut" />
  <aop:advisor advice-ref="txAdvisor" pointcut-ref="userServicePointcut" />
</aop:config>

 

 6 DAO中使用HibernateTemplate

 6.1 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" xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-3.0.xsd
   http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
 <context:annotation-config /> 
 <context:component-scan base-package="com.procrate" />

 <!-- dataSource -->
 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
  destroy-method="close">
  <property name="driverClassName" value="${jdbc.driverClassName}" />
  <property name="url" value="${jdbc.url}" />
  <property name="username" value="${jdbc.username}" />
  <property name="password" value="${jdbc.password}" />
 </bean>

 <!-- sessionFactory -->
 <bean id="sessionFactory"
  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="packagesToScan">
   <list>
    <value>com.procrate.model</value>
   </list>
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
    <prop key="hibernate.show_sql">true</prop>
   </props>
  </property>
 </bean>

 <!-- transactionManager -->
 <bean id="transactionManager"
  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory" />
 </bean>

 <!-- aop事务管理的XML配置 -->
 <aop:config>
  <aop:pointcut expression="execution(public * com.procrate.service..*.*(..))"
   id="userServicePointcut" />
  <aop:advisor advice-ref="txAdvisor" pointcut-ref="userServicePointcut" />
 </aop:config>
 <tx:advice id="txAdvisor" transaction-manager="transactionManager">
  <tx:attributes>
   <tx:method name="get*" read-only="true" />
   <tx:method name="*" />
  </tx:attributes>
 </tx:advice>
 
 <!-- HibernateTemplate -->
 <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
  <property name="sessionFactory" ref="sessionFactory"/>
 </bean>
 
 <context:property-placeholder location="classpath:jdbc.properties"/>
</beans>

 

 6.2 在DAO中注入HibernateTemplate,而不是用SessionFactory

 

7 添加Interceptor(登陆检查)

 

7.1 创建拦截器类,实现AbstractInterceptor抽象类,重写intercept方法,如下
package com.procrate.common.interceptor;

import java.util.Map;

import org.apache.log4j.Logger;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.procrate.action.UserLoginAction;
import com.procrate.common.constants.Constants;
import com.procrate.model.User;


public class AuthorityInterceptor extends AbstractInterceptor {
 
 private static final long serialVersionUID = 5553450256042738643L;
 private Logger log;

 

 @Override
 public String intercept(ActionInvocation actionInvocation) throws Exception {
  
  log = Logger.getLogger(this.getClass());
  log.debug("begin check login interceptor!");

        // 对LoginAction不做该项拦截
        Object action = actionInvocation.getAction();

        if (action instanceof UserLoginAction) {
            System.out.println("exit check login, because this is login action.");
            return actionInvocation.invoke();
        }

        // 确认Session中是否存在LOGIN
        Map<String, Object> session = actionInvocation.getInvocationContext().getSession();
        User user = (User) session.get(Constants.KEY_SESSION_USER);

        if (user != null) {

            // 存在的情况下进行后续操作。
            log.debug("already login!");
            return actionInvocation.invoke();
           
        } else {

            // 否则终止后续操作,返回LOGIN
            log.debug("no login, forward login page!");
            return Action.LOGIN;
        }
 }
}

 

7.2 配置struts.xml文件,这里有多种方法,一种可以定义一个包,把需要的拦截器加在里面,其他的包可以继承这个包(如下),还有一种就是把拦截器配置在需要的包里面(略)。

 <package name="struts-interceptor" extends="struts-default">
  <interceptors>
   <!-- 自定义拦截器,登陆检查 -->
   <interceptor name="authorityInterceptor" class="com.procrate.common.interceptor.AuthorityInterceptor"></interceptor>
   <!-- 拦截器栈 -->
   <interceptor-stack name="myInterceptor">
    <!-- Struts2(XWork)提供的拦截器   -->
    <!-- 输出Action执行的时间   -->
    <interceptor-ref name="timer" />
    <!-- 输出Action的名字   -->
    <interceptor-ref name="logger" />
    <!-- 引用自定义拦截器 -->
    <interceptor-ref name="authorityInterceptor" />
    <!-- 必须加-->
    <interceptor-ref name="defaultStack" />
   </interceptor-stack>
  </interceptors>
  <default-interceptor-ref name="myInterceptor" />
 </package>

 

 8 Ajax验证(dojo)

 8.1 添加包struts2-dojo-plugin-2.2.3.1.jar

 

 

 

 

 

 

 

 

 

 

 

 

 

 

   

 

 

 

posted on 2011-10-26 23:52  AFH  阅读(943)  评论(0编辑  收藏  举报