Spring应用之整合(Security,MVC,Hibernate)

Spring与Hibernate整合

事务的播特性

  1. propagation_required:使用当前事务,无则创建开启
  2. propagation_supports:使用当前事务,无则非事务执行
  3. propagation_mandatory:使用当前事务,无则抛出异常
  4. propagation_requires_new:当前事务挂起,开启一个新事务
  5. propagation_not_supported:挂起当前事务,非事务执行
  6. propagation_never:非事务执行,若存在一个活动事务,则抛出异常
  7. propagation_nested:Spring特有,运行在当前事务的嵌套事务中,无则同propagation_required

事务的隔离级别

  1. isolation_default:Spring特有,使用后端数据库默认的隔离级别,另外四个与JDBC的隔离级别相对应
  2. isolation_read_uncommitted:允许其他事务看到当前事务未提交的数据,可能产生脏读,不可重复读和幻读(事务最低的隔离级别)
  3. isolation_read_commited:保证一个事务修改的数据提交后才能被另外一个事务读取
  4. isolation_repeatable_read:提交数据只读,防止脏读,不可重复读,但可能出现幻像读
  5. isolation_serializable:事务被处理为顺序执行,防止脏读,不可重复读,幻读(花费代价最高,最可靠的事务隔离级别)

声明式事务配置

  1. 配置SessionFactory
  2. 配置事务管理器
  3. 事务的传播特性
  4. 那些类那些方法使用事务

注意加入连接池依赖包:

<dependency>
    <groupId>commons-dbcp</groupId>
    <artifactId>commons-dbcp</artifactId>
</dependency>

配置示例:

<?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.2.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <aop:aspectj-autoproxy proxy-target-class="true"/>
    <context:annotation-config/>
    <context:component-scan base-package="com.golf" />
    <context:property-placeholder location="classpath:jdbc-prod.properties"/>

    <!-- dataSource -->
    <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="initialSize" value="1"/>
        <property name="minIdle" value="2"/>
        <property name="maxActive" value="200"/>
        <property name="maxIdle" value="30"/>
        <property name="maxWait" value="1000"/>  
        <property name="removeAbandoned" value="true"/>
        <!-- <property name="logAbandoned" value="true"/>   -->
        <property name="validationQuery" value="select 1 from dual"/>
        <property name="testOnBorrow" value="true"/>
    </bean>

    <!-- 配置sessionFactory  -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.id.new_generator_mappings">true</prop>
                <prop key="hibernate.show_sql">${hibernate.show.sql}</prop>
                <prop key="hibernate.format_sql">${hibernate.format.sql}</prop>
                <!-- <prop key="javax.persistence.validation.mode">none</prop> -->
            </props>
        </property>
        <property name="packagesToScan">
            <list>
                <value>com.golf.entity</value>
            </list>
        </property>
    </bean>

    <!-- 声明式事务 -->
    <!-- 事务管理器 -->
    <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <!-- 事务的传播特性 -->
    <tx:advice id="txAdvice" transaction-manager="txManager" >
        <tx:attributes>
            <tx:method name="list*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="get*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="detail*" propagation="REQUIRED" read-only="true" />
            <tx:method name="test*" propagation="REQUIRED" read-only="true"  />
            <tx:method name="sendMail" propagation="REQUIRED" read-only="true" no-rollback-for="Exception"/>
            <tx:method name="getGrantedAuthorities" propagation="REQUIRED" read-only="false"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
    <!-- 参与事务的方法 -->
      <aop:config>
        <aop:pointcut expression="execution(* com.golf.service.*.*(..))" id="mySearchService"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="mySearchService" order="2"/>
    </aop:config> 

    <!-- 声明式日志 -->
    <bean id="loggerHandler" class="com.cj.support.aop.LoggerHandler"/>
    <aop:config>
        <aop:aspect ref="loggerHandler" order="1"> 
            <aop:pointcut expression="execution(public * com.golf.service.*.*(..))" id="method"/>
            <aop:around method="logAround" pointcut-ref="method" />
        </aop:aspect>
    </aop:config>
</beans>

综合示例(Security,MVC,Hibernate)

这里项目名为golf

注意加入这些框架的依赖包:

  • Spring
  • SpringMVC
  • SpringSecurity
  • Hibernate

web.xml

加载Spring&SpringSecurity&SpringMVC

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

   <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:beans.xml,classpath*:golf-security.xml</param-value>
    </context-param>

    <!-- Spring -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- Spring刷新Interceptor防止内存泄漏  -->
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>
    <!-- 设置session 超时时间为20分钟  -->
    <session-config>
        <session-timeout>60</session-timeout>
    </session-config>
    <!--通过HttpSessionEventPublisher,让servelt容器通知Spring Security session生命周期的事-->
    <listener>
        <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
    </listener>

  <!-- 使用Spring中的过滤器解决在请求和应答中的中文乱码问题 -->
    <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>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

   <!-- Spring Secutiry 过滤器链配置  -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

  <!-- Spring MVC -->
   <servlet>
        <servlet-name>golf</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>golf</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

beans.xml

配置Spring(加入Hibernate配置)

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

    <task:annotation-driven/>
    <aop:aspectj-autoproxy proxy-target-class="true"/>

    <context:annotation-config/>
    <!-- scan排除Controller-->
    <context:component-scan base-package="com.golf" >
        <context:exclude-filter type="regex" expression="com.golf.controller.*"/>
    </context:component-scan>
    <context:property-placeholder location="classpath:jdbc-prod.properties"/>

    <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="initialSize" value="1"/>
        <property name="minIdle" value="2"/>
        <property name="maxActive" value="200"/>
        <property name="maxIdle" value="30"/>
        <property name="maxWait" value="1000"/>
        <property name="removeAbandoned" value="true"/>
        <!-- <property name="logAbandoned" value="true"/>   -->
        <property name="validationQuery" value="select 1 from dual"/> 
        <property name="testOnBorrow" value="true"/>
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.id.new_generator_mappings">true</prop>
                <prop key="hibernate.show_sql">${hibernate.show.sql}</prop>
                <prop key="hibernate.format_sql">${hibernate.format.sql}</prop>
                <!-- <prop key="javax.persistence.validation.mode">none</prop> -->
            </props>
        </property>
        <property name="packagesToScan">
            <list>
                <value>com.golf.entity</value>
            </list>
        </property>
    </bean>

    <!-- 声明式事务 -->
    <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <tx:advice id="txAdvice" transaction-manager="txManager" >
        <tx:attributes>
            <tx:method name="list*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="get*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="detail*" propagation="REQUIRED" read-only="true" />
            <tx:method name="test*" propagation="REQUIRED" read-only="true"  />
            <tx:method name="sendMail" propagation="REQUIRED" read-only="true" no-rollback-for="Exception"/>
            <tx:method name="getGrantedAuthorities" propagation="REQUIRED" read-only="false"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
     <aop:config>
        <aop:pointcut expression="execution(* com.golf.service.*.*(..))" id="mySearchService"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="mySearchService" order="2"/>
    </aop:config>

    <!-- 声明式日志 -->
    <bean id="loggerHandler" class="com.cj.support.aop.LoggerHandler"/>
    <aop:config>
        <aop:aspect ref="loggerHandler" order="1"> 
            <aop:pointcut expression="execution(public * com.golf.service.*.*(..))" id="method"/>
            <aop:around method="logAround" pointcut-ref="method" />
        </aop:aspect>
    </aop:config>

    <!-- Jackson ObjectMapper -->
    <bean id="myObjectMapper" class="com.fasterxml.jackson.databind.ObjectMapper">
        <property name="serializationInclusion">
             <value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
         </property>
    </bean>
</beans>

xxx-servlet.xml

配置SpringMVC

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

    <!-- 在Controlller中使用SpringSecurity SpEL注解,需配置:-->
    <sec:global-method-security pre-post-annotations="enabled"/>

    <!-- 使用Spring MVC所提供的注解驱动特性 -->
    <mvc:annotation-driven>
      <mvc:message-converters>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                 <property name="objectMapper" ref="myObjectMapper"/>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <context:component-scan base-package="com.golf.controller" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"  />
        <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
    </context:component-scan>

    <mvc:interceptors>
        <mvc:interceptor>
            <!-- <mvc:mapping path="/**" />
            <mvc:exclude-mapping path="/resources/**"/> -->
            <mvc:mapping path="/api/**" />
            <bean class="com.cj.support.interceptor.MyHandlerPaginationInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

    <mvc:resources location="/resources/" mapping="/resources/**"/> <!-- 会建立一个服务于静态资源的处理器 -->
    <!-- Handler Static Resources: Order Last -->
    <mvc:default-servlet-handler/>

    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="mediaTypes">
            <map>
                <!-- <entry key="html" value="text/html"/> -->
                <entry key="json" value="application/json"/>
            </map>
        </property>
        <!-- <property name="defaultContentType" value="text/html"/> -->
        <property name="viewResolvers">
            <list>
                <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
                    <property name="prefix" value="/WEB-INF/"/>
                    <property name="suffix" value=".jsp"/>
                </bean> 
            </list>
        </property>
        <property name="defaultViews">
            <list>
                <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" >
                    <property name="objectMapper" ref="myObjectMapper" />
                </bean>
            </list>
        </property>
    </bean>

    <!-- Upload -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="1000000"/>
    </bean>
</beans>

xxx-security.xml

配置SpringSecurity: 这里使用UsernamePassword认证和ldap认证

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

    <sec:http pattern="/resources/**"  security="none"/>

    <!-- Golf Web Security -->
    <sec:http  auto-config="false" use-expressions="true" entry-point-authentication-manager-ref="myAuthenticationManager">
        <sec:anonymous key="test" granted-authority="Guest" username="guest"/>

        <sec:intercept-url pattern="/page-**/**" access="authenticated"/>
        <sec:intercept-url pattern="/admin-**/**" access="hasRole('Admin')"/>

        <sec:intercept-url pattern="/api/payments" method="POST" access="hasRole('RequestUser')"/>
        <sec:intercept-url pattern="/api/payments/*/payed" method="POST" access="hasRole('Payment')"/>
        <sec:intercept-url pattern="/api/receivers" method="GET" access="hasAnyRole('RequestUser','Admin')"/>
        <sec:intercept-url pattern="/api/receipts" method="POST" access="authenticated and authentication.extra.orgType=='LingShan'"/>

        <sec:intercept-url pattern="/api/users/**" access="hasRole('Admin')"/>
        <sec:intercept-url pattern="/api/roles" access="hasRole('Admin')"/>
        <sec:intercept-url pattern="/api/receivers" method="POST" access="hasRole('Admin')"/>
        <sec:intercept-url pattern="/api/receivers/*/*" method="GET" access="hasRole('Admin')"/>

        <sec:intercept-url pattern="/api/**" access="authenticated"/>
        <sec:intercept-url pattern="/" access="permitAll"/>
        <sec:intercept-url pattern="/login" access="permitAll"/>
        <sec:intercept-url pattern="/auth" access="permitAll"/>
        <sec:intercept-url pattern="/**" access="hasRole('Admin')"/>

        <sec:form-login login-processing-url="/api/j_spring_security_check" username-parameter="username" password-parameter="password"
            login-page="/login" authentication-failure-url="/auth?error=UnAuthenticated" default-target-url="/auth" />
        <sec:logout logout-success-url="/auth" logout-url="/api/j_spring_security_logout"/>
        <sec:session-management>
            <sec:concurrency-control max-sessions="1" expired-url= "/login?error=This session has been expired"/>
        </sec:session-management>
        <sec:request-cache ref="nullRequestCache"/>
    </sec:http>

    <bean id="nullRequestCache" class="org.springframework.security.web.savedrequest.NullRequestCache"/>

    <sec:authentication-manager id="myAuthenticationManager" >
        <sec:authentication-provider user-service-ref="myUserDetailsService" />
        <sec:authentication-provider ref="ldapAuthenticationProvider"/>
    </sec:authentication-manager>
    <bean id="myUserDetailsService" class="com.golf.service.MyUserDetailsService"/>

     <bean id="ldapAuthenticationProvider" class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider">
        <constructor-arg name="authenticator" ref="bindAuthenticator"/>
        <constructor-arg name="authoritiesPopulator" ref="ldapAuthoritiesPopulator"/>
    </bean>
     <bean id="bindAuthenticator" class="org.springframework.security.ldap.authentication.BindAuthenticator">
        <constructor-arg name="contextSource" ref="ldapServer"/>
        <property name="userSearch" ref="ldapSearch">
        </property>
    </bean>
    <bean id="ldapAuthoritiesPopulator" class="com.cj.support.security.ldap.MyLdapAuthoritiesPopulator"/>

    <!-- Ldap Server & Search Config -->
     <bean id="ldapSearch" class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch" >
      <constructor-arg name="searchBase" value="ou=people"/>   <!-- user-search-base -->
      <constructor-arg name="searchFilter" value="(uid={0})"/> <!-- user-search-filter -->
      <constructor-arg name="contextSource" ref="ldapServer"/>
    </bean>
    <sec:ldap-server id="ldapServer" url="ldap://xxxx/o=xxxx"  />
</beans>
public class MyUserDetailsService implements UserDetailsService
{
    static Logger logger = Logger.getLogger(GolfUserDetailsService.class);  
    private ISecurityService securityService;
    public ISecurityService getSecurityService(){
        return securityService;
    }
    @Inject
    public void setSecurityService(ISecurityService securityService){
        this.securityService = securityService;
    }

    @Override
    public UserDetails loadUserByUsername(String account)
            throws UsernameNotFoundException
    {
        List<GrantedAuthority> glist=securityService.getGrantedAuthorities(account);
        if(glist==null || glist.size()==0)
            throw new UsernameNotFoundException("No GrantedAuthority");
        SysUser user=(SysUser)securityService.getUser(account);
        if(user!=null )
            return new MyUser(account,user.getPwd(),glist); //MyUser implements UserDetails
        throw new UsernameNotFoundException("Not Found");
    }
}