Java绿地(~ming~)

Java 草地

常用链接

统计

最新评论

ssh实现的包含acegi的项目框架(注释少)

一.Hibernate持久化层
1.model:
a.User.java

package com.witbridge.payroll.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.userdetails.UserDetails;

@SuppressWarnings(
"unchecked")
public class User implements Serializable, UserDetails {
    
private static final long serialVersionUID = 2289410331437985768L;
    
    
private Integer id;
    
private String username;
    
private String password;
    
private String email;
    
private boolean enabled;
    
private boolean accountExpired;
    
private boolean accountLocked;
    
private boolean credentialsExpired;
    
private Integer associateId;
    
private List roles = new ArrayList();
    
    
//~============================getter & settter
    public Integer getId() {
        
return id;
    }


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

    
    
public boolean isAccountExpired() {
        
return accountExpired;
    }


    
public void setAccountExpired(boolean accountExpired) {
        
this.accountExpired = accountExpired;
    }


    
public boolean isAccountLocked() {
        
return accountLocked;
    }


    
public void setAccountLocked(boolean accountLocked) {
        
this.accountLocked = accountLocked;
    }


    
public boolean isCredentialsExpired() {
        
return credentialsExpired;
    }


    
public void setCredentialsExpired(boolean credentialsExpired) {
        
this.credentialsExpired = credentialsExpired;
    }


    
public void setEnabled(boolean enabled) {
        
this.enabled = enabled;
    }


    
public void setPassword(String password) {
        
this.password = password;
    }


    
public void setUsername(String username) {
        
this.username = username;
    }

    
    
public String getEmail() {
        
return email;
    }


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

    
    
public List getRoles() {
        
return roles;
    }


    
public void setRoles(List roles) {
        
this.roles = roles;
    }


    
public void addRole(Role role) {
        roles.add(role);
    }

    
    
public GrantedAuthority[] getAuthorities() {
        
return (GrantedAuthority[]) roles.toArray(new GrantedAuthority[0]);
    }


    
public String getPassword() {
        
return password;
    }


    
public String getUsername() {
        
return username;
    }


    
public boolean isAccountNonExpired() {
        
return !isAccountExpired();
    }


    
public boolean isAccountNonLocked() {
        
return !isAccountLocked();
    }


    
public boolean isCredentialsNonExpired() {
        
return !isCredentialsExpired();
    }


    
public boolean isEnabled() {
        
return enabled;
    }


    
public Integer getAssociateId() {
        
return associateId;
    }


    
public void setAssociateId(Integer associateId) {
        
this.associateId = associateId;
    }

}


Role.java
package com.witbridge.payroll.model;

import java.io.Serializable;

import org.acegisecurity.GrantedAuthority;


public class Role implements Serializable, GrantedAuthority {
    
    
private static final long serialVersionUID = -3187100981785730494L;
    
    
private Integer id;
    
private String name;
    
    
//~=================================Constructor
    public Role() {
    }

    
public Role(Integer id, String name) {
        
this.id = id;
        
this.name = name;
    }

    
    
//~=================================getter & setter
    public Integer getId() {
        
return id;
    }

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

    
public String getName() {
        
return name;
    }

    
public void setName(String name) {
        
this.name = name;
    }

    
    
public String getAuthority() {
        
return name;
    }

}


UserRole:
package com.witbridge.payroll.model;

import java.io.Serializable;

public class UserRole implements Serializable {
    
private static final long serialVersionUID = 3627077608786533159L;

    
private Integer userId;
    
private Integer roleId;

    
public Integer getRoleId() {
        
return roleId;
    }


    
public void setRoleId(Integer roleId) {
        
this.roleId = roleId;
    }


    
public Integer getUserId() {
        
return userId;
    }


    
public void setUserId(Integer userId) {
        
this.userId = userId;
    }


}


测试的Demo:Person.java
package com.witbridge.payroll.model;

public class Person {
   
private Integer id;
   
private String username;
   
private String password;

public Integer getId() {
    
return id;
}

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

public String getPassword() {
    
return password;
}

public void setPassword(String password) {
    
this.password = password;
}

public String getUsername() {
    
return username;
}

public void setUsername(String username) {
    
this.username = username;
}

   
}



2.Hibernate映射文件
0.数据源的配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
    
<!-- DataSource definition -->
    
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        
<property name="driverClassName" value="COM.ibm.db2.jdbc.net.DB2Driver" />
        
<property name="url" value="jdbc:db2:192.168.0.120:payrolla" />
        
<property name="username" value="db2admin" />
        
<property name="password" value="db2admin" />
    
</bean>
    
<!--  
    
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
        
<property name="url" value="jdbc:mysql://localhost:3306/payroll1" />
        
<property name="username" value="root" />
        
<property name="password" value="root" />
    
</bean>
    
-->
    
<!-- Hibernate SessionFactory -->
    
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        
<property name="dataSource" ref="dataSource" />
        
<property name="mappingDirectoryLocations">
            
<list>    <value>classpath:/com/witbridge/payroll/hbm</value>    </list>
        
</property>
        
<property name="hibernateProperties">
            
<props>    
                
<prop key="hibernate.dialect">org.hibernate.dialect.DB2Dialect</prop>
                
<prop key="hibernate.show_sql">true</prop>
            
</props>
        
</property>
    
</bean>

    
<!-- Transaction manager for a single Hibernate SessionFactory -->
    
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        
<property name="sessionFactory" ref="sessionFactory" />
    
</bean>
    
</beans>




a.user.hbm

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="com.witbridge.payroll.model">
    
<class name="User" table="user" lazy="false">
        
<id name="id" column="id">
            
<generator class="identity" />
        
</id>
        
        
<property name="username" column="username" />
        
<property name="password" column="password" />
        
<property name="email" column="email" />
        
<property name="enabled" column="enabled" />
        
<property name="accountExpired" column="account_expired" />
        
<property name="accountLocked" column="account_locked" />
        
<property name="credentialsExpired" column="credentials_expired" />
        
<property name="associateId" column="associate_id"></property>
    
</class>
</hibernate-mapping>

b.role.hbm

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="com.witbridge.payroll.model">
    
<class name="Role" table="role" lazy="false">
        
<id name="id" column="id">
            
<generator class="native" />
        
</id>
        
        
<property name="name" column="name" />

    
</class>
</hibernate-mapping>

c.user_role.hbm

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="com.witbridge.payroll.model">
    
<class name="UserRole" table="user_role" lazy="false">
        
<composite-id>
            
<key-property name="userId" column="user_id"/>
            
<key-property name="roleId" column="role_id"/>
        
</composite-id>
    
</class>
</hibernate-mapping>

d.person.hbm

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse 
- Hibernate Tools
-->
<hibernate-mapping package="com.witbridge.payroll.model">
    
<class name="Person" table="PERSON" schema="DB2ADMIN" lazy="false">
        
<id name="id" type="java.lang.Integer">
            
<column name="ID" />
            
<generator class="identity"></generator>
        
</id>
        
<property name="username" type="java.lang.String">
            
<column name="USERNAME" length="10" />
        
</property>
        
<property name="password" type="java.lang.String">
            
<column name="PASSWORD" length="10" />
        
</property>
    
</class>
</hibernate-mapping>


 二.Spring的业务方法层
1.PersonService.java

package com.witbridge.payroll.service;
import java.util.List;

import org.acegisecurity.annotation.Secured;
import org.springframework.transaction.annotation.Transactional;

import com.witbridge.payroll.model.Person;
@Transactional
public interface PersonService {
    
    @Secured(
"ADMIN")
    
public String addAssociate(Person person);
    
    @Transactional(readOnly
=true)
    @Secured(
{"ADMIN","HR"})
    
public List<Person> findAllPerson();
    
    
public Person findPersonById(Integer id);
    
    
public void delete(Integer id);
    
    
public void updatePerson(Person person);
}



2.PersonServiceImpl.java

 

package com.witbridge.payroll.service.impl;

import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.witbridge.payroll.model.Person;
import com.witbridge.payroll.service.PersonService;

public class PersonServiceImpl extends HibernateDaoSupport implements PersonService {
 
    
public String addAssociate(Person person) {
  getHibernateTemplate().saveOrUpdate(person);
  
return person.getUsername();
 }


 @SuppressWarnings(
"unchecked")
 
public List<Person> findAllPerson() {
  String hql
="from Person";
   
return  getHibernateTemplate().find(hql);
 }


 
public Person findPersonById(Integer id) {
  
return (Person) getHibernateTemplate().load(Person.class, id);
 }


 
public void delete(Integer id) {
  String hql
="delete from Person where id=?";
  getHibernateTemplate().bulkUpdate(hql, id);
  
 }


 
public void updatePerson(Person person) {
  getHibernateTemplate().update(person);
  
 }
  

}



3.Spring的service注入
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans default-autowire="byName">
    
<!-- Auto proxy driven by JDK 5+ Annotation -->
    
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" />
    
    
<bean class="org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor">
        
<property name="transactionInterceptor" ref="transactionInterceptor" />
    
</bean>
    
    
<bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
        
<property name="transactionManager" ref="transactionManager" />
        
<property name="transactionAttributeSource">
            
<bean class="org.springframework.transaction.annotation.AnnotationTransactionAttributeSource"/>
        
</property>
    
</bean>
    
    
        
    
<!--payroll group:Business manager definitions ,需要的dao采用自动装配,并将service类实例化提供给action -->
    
<bean id="userManager" class="com.witbridge.payroll.service.impl.UserManagerImpl" />
    
<bean id="personService" class="com.witbridge.payroll.service.impl.PersonServiceImpl"/>
    
<bean id="roleService" class="com.witbridge.payroll.service.impl.RoleServiceImpl"/> 
     
</beans>

三.Spring的acegi:
1.service:
package com.witbridge.payroll.service;

import org.acegisecurity.userdetails.UserDetailsService;
import org.springframework.transaction.annotation.Transactional;


@Transactional
public interface UserManager extends UserDetailsService {

}

 

2.serviceimpl:

package com.witbridge.payroll.service.impl;

import java.util.List;

import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.witbridge.payroll.model.User;
import com.witbridge.payroll.service.UserManager;

public class UserManagerImpl extends HibernateDaoSupport implements UserManager {

    
public UserDetails loadUserByUsername(String username)
            
throws UsernameNotFoundException, DataAccessException {
        
//get user by username
        String hql = "from User u where u.username=?";
        List list 
= getHibernateTemplate().find(hql, username);
        
if (list.isEmpty()) {
            
throw new UsernameNotFoundException("Username:" + username + " not found!");
        }

        
        User user 
= (User) list.get(0);
        
        
//get user's roles
        hql = "select new Role(r.id, r.name) from UserRole ur, Role r where ur.userId=? and ur.roleId=r.id";
        List roles 
= getHibernateTemplate().find(hql, user.getId());
        user.setRoles(roles);
        
        
return user;
    }

    
}


3.acegi的配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

    
<bean id="filterChainProxy" class="org.acegisecurity.util.FilterChainProxy">
        
<property name="filterInvocationDefinitionSource">
            
<value>
                CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
                PATTERN_TYPE_APACHE_ANT
                
/**=httpSessionContextIntegrationFilter,logoutFilter,authenticationProcessingFilter,securityContextHolderAwareRequestFilter,rememberMeProcessingFilter,anonymousProcessingFilter,exceptionTranslationFilter,filterInvocationInterceptor
            </value>
        </property>
    </bean>
    
<!-- ================================================== Filters definition ===================================================-->
    <!-- the filters have three sepatate parts:ProcessingFilter, FilterSecurityInterceptor,ProviderManager-->
    
    <!-- save the username and password in the securityContext -->
    <bean id="httpSessionContextIntegrationFilter" class="org.acegisecurity.context.HttpSessionContextIntegrationFilter"/>

    <bean id="logoutFilter" class="org.acegisecurity.ui.logout.LogoutFilter">
        <constructor-arg value="/login.jsp"/> <!-- URL redirected to after logout -->
        <constructor-arg>
            <list>
                <ref bean="rememberMeServices"/>
                <bean class="org.acegisecurity.ui.logout.SecurityContextLogoutHandler"/>
            </list>
        </constructor-arg>
        <property name="filterProcessesUrl" value="/logout" />
    </bean>

    <bean id="authenticationProcessingFilter" class="org.acegisecurity.ui.webapp.AuthenticationProcessingFilter">
        <property name="authenticationManager" ref="authenticationManager"/>
        <property name="authenticationFailureUrl" value="/login.jsp?error=true"/>
        <property name="defaultTargetUrl" value="/login.do?method=login"/>
        <property name="filterProcessesUrl" value="/login"/>
        <property name="rememberMeServices" ref="rememberMeServices"/>
    </bean>
  
    <bean id="securityContextHolderAwareRequestFilter" class="org.acegisecurity.wrapper.SecurityContextHolderAwareRequestFilter"/>

    <bean id="rememberMeProcessingFilter" class="org.acegisecurity.ui.rememberme.RememberMeProcessingFilter">
        <property name="authenticationManager" ref="authenticationManager"/>
        <property name="rememberMeServices" ref="rememberMeServices"/>
    </bean>

    <bean id="anonymousProcessingFilter" class="org.acegisecurity.providers.anonymous.AnonymousProcessingFilter">
        <property name="key" value="acegi_anonymous"/>
        <property name="userAttribute" value="anonymousUser,ANONYMOUS"/>
    </bean>

    <bean id="exceptionTranslationFilter" class="org.acegisecurity.ui.ExceptionTranslationFilter">
        <property name="authenticationEntryPoint">
            <bean class="org.acegisecurity.ui.webapp.AuthenticationProcessingFilterEntryPoint">
                <property name="loginFormUrl" value="/"/>
                <property name="forceHttps" value="false"/>
            </bean>
        </property>
        <property name="accessDeniedHandler">
            <bean class="org.acegisecurity.ui.AccessDeniedHandlerImpl">
                <property name="errorPage" value="/common/accessDenied.jsp"/>
            </bean>
        </property>
    </bean>
    
    
    
    
    
    
    <!-- payroll group:整个security配制只需要改变此处,对您开发的url进行访问权限控制,基本格式为:/目录名/页面名称*=权限名 -->
    <bean id="filterInvocationInterceptor" class="org.acegisecurity.intercept.web.FilterSecurityInterceptor">
        <property name="authenticationManager" ref="authenticationManager"/>
        <property name="accessDecisionManager" ref="accessDecisionManager" />
        <property name="objectDefinitionSource">
            <value>
                CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
                PATTERN_TYPE_APACHE_ANT
                /associate/**=FD,ADMIN
                
                /**=IS_AUTHENTICATED_ANONYMOUSLY  <!-- must be the last line -->
            </value>
        </property>
    </bean>











<!-- ========================================== End filters definition =========================================== -->

    <!-- Authentication Manager -->
    <bean id="authenticationManager" class="org.acegisecurity.providers.ProviderManager">
        <property name="providers">
            <list>
                <ref local="daoAuthenticationProvider"/>
                <bean class="org.acegisecurity.providers.anonymous.AnonymousAuthenticationProvider">
                    <property name="key" value="acegi_anonymous"/>
                </bean>
                <bean class="org.acegisecurity.providers.rememberme.RememberMeAuthenticationProvider">
                    <property name="key" value="acegi_rememberme"/>
                </bean>
            </list>
        </property>
    </bean>
    
    <!-- userDetailsService通过注入的方式进行权限验证 -->
    <bean id="daoAuthenticationProvider" class="org.acegisecurity.providers.dao.DaoAuthenticationProvider">
        <property name="userDetailsService" ref="userManager"/>
        <property name="userCache" ref="userCache" />
    </bean>
    <bean id="userCache" class="org.acegisecurity.providers.dao.cache.EhCacheBasedUserCache">
        <property name="cache">
            <bean class="org.springframework.cache.ehcache.EhCacheFactoryBean">
                <property name="cacheManager">
                    <bean class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"/>
                </property>
                <property name="cacheName" value="userCache"/>
            </bean>
        </property>
    </bean>
    
    <!-- Access Decision Manager -->
    <bean id="accessDecisionManager" class="org.acegisecurity.vote.AffirmativeBased">
        <property name="decisionVoters">
            <list>
                <bean class="org.acegisecurity.vote.RoleVoter">
                    <property name="rolePrefix" value="" />
                </bean>
                <bean class="org.acegisecurity.vote.AuthenticatedVoter"/>
            </list>
        </property>
        <property name="allowIfAllAbstainDecisions" value="false"/>
    </bean>

    <!-- RememberMe Service,save the user's messages into Cookies -->
    <bean id="rememberMeServices" class="org.acegisecurity.ui.rememberme.TokenBasedRememberMeServices">
        <property name="userDetailsService" ref="userManager"/>
        <property name="key" value="acegi_rememberme"/>
    </bean>

<!-- =======================Method Security Interceptor Driven by Annotation Auto Proxy ============================== -->
     <!-- This bean has been defined in applicationContext-service.xml!
     <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>
     -->
    
    
    <bean class="org.acegisecurity.intercept.method.aopalliance.MethodDefinitionSourceAdvisor" autowire="constructor" />

    <bean id="methodSecurityInterceptor" class="org.acegisecurity.intercept.method.aopalliance.MethodSecurityInterceptor">
        <property name="validateConfigAttributes" value="true" />
        <property name="authenticationManager" ref="authenticationManager" />
        <property name="accessDecisionManager" ref="accessDecisionManager" />
        <property name="objectDefinitionSource">
            <bean class="org.acegisecurity.intercept.method.MethodDefinitionAttributes">
                <property name="attributes"><bean class="org.acegisecurity.annotation.SecurityAnnotationAttributes" />
                </property>
            </bean>
        </property>
    </bean>
 
</beans>

  四.struts
1.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">
    
    
<!-- load the Spring xml files -->
    
    
<context-param>
        
<param-name>contextConfigLocation</param-name>
        
<param-value>
            
/WEB-INF/applicationContext-*.xml
        
</param-value>
    
</context-param>
    
        
<!-- Spring Context Listener -->
    
    
<listener>
        
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    
</listener>
    
    
    
<!-- Encoding Filter -->
    
<filter>
        
<filter-name>CharacterEncodingFilter</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>
        
<init-param>
            
<param-name>forceEncoding</param-name>
            
<param-value>true</param-value>
        
</init-param>
    
</filter>
    
<filter-mapping>
        
<filter-name>CharacterEncodingFilter</filter-name>
        
<url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <!-- Acegi Filter -->
    <filter>
        <filter-name>Acegi Filter Chain Proxy</filter-name>
        <filter-class>org.acegisecurity.util.FilterToBeanProxy</filter-class>
        <init-param>
            <param-name>targetClass</param-name>
            <param-value>org.acegisecurity.util.FilterChainProxy</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>Acegi Filter Chain Proxy</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    
    <!-- Struts Config -->
    <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>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>action</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    <!-- Session time out(minute) definition -->
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
    
    <!-- Welcome file difinition -->
    <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>
    
    <!-- Error pages -->
    <error-page>
        <error-code>500</error-code>
        <location>/common/error.jsp</location>
    </error-page>
    
</web-app>


2.struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">

<struts-config>
    
<!-- payroll group:add your form-beans -->
    
<form-beans>
    
    
<form-bean name="personForm" type="org.apache.struts.validator.DynaValidatorForm">
       
<form-property name="person" type="com.witbridge.payroll.model.Person"></form-property>
    
</form-bean>
    
    
<form-bean name="roleForm" type="org.apache.struts.validator.DynaValidatorForm">
       
<form-property name="role" type="com.witbridge.payroll.model.Role"></form-property>
    
</form-bean>
    
    
</form-beans>



    
<global-exceptions />

    
<global-forwards />
    
    
    
    
<!-- payroll group:add your action mappings -->
    
<action-mappings>
        
        
<action path="/login"
                type
="com.witbridge.payroll.action.LoginAction"
                parameter
="method">
            
<forward name="mainPage" path="/associate/person.jsp" />
        
</action>
           
    
<action path="/person" 
    type
="com.witbridge.payroll.action.PersonAction"
    name
="personForm"
    parameter
="method"
    scope
="request"
    validate
="false"
    input
="/person.jsp">
    
<forward name="success" path="/associate/person.jsp" />
    
<forward name="findAll" path="/associate/findPerson.jsp"></forward>
    
<forward name="onePerson" path="/associate/onePerson.jsp"></forward>
    
<forward name="failure" path="/person.jsp" />
    
</action>
    
    
<action path="/role" 
    type
="com.witbridge.payroll.action.RoleAction"
    name
="roleForm"
    parameter
="method"
    scope
="request"
    validate
="false"
    input
="/manage/createroll.jsp">
    
<forward name="success" path="/manage/createsuccess.jsp" />
    
<forward name="failure" path="/manage/failure.jsp" />
    
</action>
    
    
        
        
    
    
</action-mappings>
    
    
    
<!-- apply Delegate Model for Spring Framework -->
    
<controller    processorClass="org.springframework.web.struts.DelegatingRequestProcessor" />
    
    
<message-resources parameter="com.witbridge.payroll.resource.ApplicationResources" null="false" />
    
    
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
        
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml, /WEB-INF/validation.xml"/>
    
</plug-in>
   
   
   
</struts-config>


3.action:
package com.witbridge.payroll.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.acegisecurity.context.SecurityContextHolder;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.witbridge.payroll.common.BaseDispatchAction;
import com.witbridge.payroll.model.User;

public class LoginAction extends BaseDispatchAction {

    
public ActionForward login(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) 
throws Exception {
        
        User user 
= (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        
        
        request.getSession().setAttribute(
"user", user);
        
        
return mapping.findForward("mainPage");
    }


}


package com.witbridge.payroll.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.validator.DynaValidatorForm;

import com.witbridge.payroll.model.Person;
import com.witbridge.payroll.service.PersonService;




public class PersonAction extends DispatchAction {
    
//通过注入方式得到bean,action中一定要有set方法
    private PersonService personService;
    
    
public void setPersonService(PersonService personService) {
        
this.personService = personService;
    }


    
public ActionForward addPerson(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) 
throws Exception {
        
        DynaValidatorForm personForm 
= (DynaValidatorForm) form;
        Person person
=(Person) personForm.get("person");
        String success
=personService.addAssociate(person);
        
        
if(success!=nullreturn mapping.findForward("success");  }
        
        
else return mapping.findForward("failure");
    }


    
public ActionForward getAllPerson(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) 
throws Exception {
       List personList
=new ArrayList();
       personList
=personService.findAllPerson();
       request.setAttribute(
"personList", personList);
       
return mapping.findForward("findAll");
    }

    
    
public ActionForward getPersonById(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) 
throws Exception {
       Integer id
=new Integer(request.getParameter("id"));
        Person person
=new Person();
       person
=personService.findPersonById(id);
       request.setAttribute(
"person", person);
       
return mapping.findForward("onePerson");
    }


    
    
public ActionForward updatePerson(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) 
throws Exception {
        DynaValidatorForm personForm 
= (DynaValidatorForm) form;
        Person person
=(Person) personForm.get("person");
        System.out.println(person.getId());
        personService.updatePerson(person);
       
return mapping.findForward("success");
    }




}



4.spring接管action的配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans default-autowire="byName">

    
<!--payroll group: action definitions -->
    
<!-- 采用delegate方式装配action ,并且所需service类也自动装配,不用getBean方式去获得-->
    
<bean name="/login" class="com.witbridge.payroll.action.LoginAction"/>
    
<bean name="/person" class="com.witbridge.payroll.action.PersonAction"/>
    
<bean name="/role" class="com.witbridge.payroll.action.RoleAction" />


</beans>

posted on 2007-09-11 15:28 mrklmxy 阅读(1206) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: