发布于 2015-11-27 09:55:57 | 122 次阅读 | 评论: 0 | 来源: PHPERZ

这里有新鲜出炉的精品教程,程序狗速度看过来!

Spring Framework 开源j2ee框架

Spring是什么呢?首先它是一个开源的项目,而且目前非常活跃;它是一个基于IOC和AOP的构架多层j2ee系统的框架,但它不强迫你必须在每一层 中必须使用Spring,因为它模块化的很好,允许你根据自己的需要选择使用它的某一个模块;它实现了很优雅的MVC,对不同的数据访问技术提供了统一的接口,采用IOC使得可以很容易的实现bean的装配,提供了简洁的AOP并据此实现Transcation Managment,等等


我前几篇分散的说了spring mvc,这一篇我完整的说一下,仅供参考,如果大家要用,

只需要改下路径就行,可能比较长,大家耐心看哦。我会在最后把工程连接贴上。

先贴hibernate的连接配置:hibernate.properties

dataSource.url=jdbc\:mysql\://127.0.0.1\:3306/dorm
dataSource.password=123456
dataSource.username=root
dataSource.driverClassName=com.mysql.jdbc.Driver
dataSource.dialect=org.hibernate.dialect.MySQL5Dialect
dataSource.hbm2ddl.auto=update
dataSource.format_sql=true
dataSource.show_sql=false


这和是与数据库连接的配置,这个不多说了。

下面我贴下log4j的日志配置log4j.properties:

#日志输出优先级有五个级别,debug,info,warn,error,fatal
#日志输出级别为info,根日志器输出目的地为stdout(控制台),logfile
log4j.rootLogger=warn, stdout,file,D  
#记录JDBC参数
log4j.logger.org.hibernate.type=info  
#记录所有的信息  
#log4j.logger.org.hibernate=INFO
#记录执行的SQL DDL语句 
log4j.logger.org.hibernate.tool.hbm2ddl=debug
#SQL  
log4j.logger.org.hibernate.SQL=debug 
#当解析查询语句时记录HQL和SQL  
#log4j.logger.org.hibernate.hql.ast.AST=DEBUG  
#HQL  
#log4j.logger.org.hibernate.hql=DEBUG

### direct log messages to stdout ###  

#控制台输出
log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
log4j.appender.stdout.Target=System.out  
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}\:%L - %m%n  

#文件输出  
log4j.appender.file=org.apache.log4j.FileAppender  
log4j.appender.file.File=${catalina.home}/log4j/test_log.log  
log4j.appender.file.layout=org.apache.log4j.PatternLayout  
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}\:%L - %m%n  

#异常文件单独输出
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File =${catalina.home}/log4j/error.log 
log4j.appender.D.Append = true
log4j.appender.D.Threshold= error 
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}\:%L - %m%n

# 应用于文件滚动输出  和 DailyRollingFileAppender的区别在于一个按时间,另一个按容量
#log4j.appender.ROLLING_FILE=org.apache.log4j.RollingFileAppender  
#log4j.appender.ROLLING_FILE.Threshold=g:/log4j/daily_error.jpg  
#log4j.appender.ROLLING_FILE.File=rolling.log  
#log4j.appender.ROLLING_FILE.Append=true  
#一个文件的最大限度
#log4j.appender.ROLLING_FILE.MaxFileSize=10KB  
#只有一个备份文件
#log4j.appender.ROLLING_FILE.MaxBackupIndex=1  
#log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout 
#log4j.appender.ROLLING_FILE.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}\:%L - %m%n

这个值得一说的是采用的spring aop拦截的controller,有人也许说controller不可拦截,实际上是可以的,

只是换个代理,另外这个把总文件输出到一个文件,把error文件输出到一个文件

好了,重头戏该开始了,下面是web.xml的配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
	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_3_0.xsd">
  <display-name></display-name>	
  
  <listener>
		<listener-class>
			org.springframework.web.context.ContextLoaderListener
		</listener-class>
	</listener>
	
	<!-- 加载spring的xml配置文件到 spring的上下文容器中 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/app*.xml,/WEB-INF/spring-shiro.xml</param-value>
	</context-param>
	
	<!--log4j配置文件加载-->  
       <context-param>      
           <param-name>log4jConfigLocation</param-name>      
           <param-value>classpath:log4j.properties</param-value>      
       </context-param>  
       <!--启动一个watchdog线程每1800秒扫描一下log4j配置文件的变化-->  
       <context-param>      
           <param-name>log4jRefreshInterval</param-name>      
           <param-value>1800000</param-value>      
       </context-param>   
       <!--spring log4j监听器-->  
       <listener>      
           <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>      
       </listener>
       <!-- 解决懒加载时由于会话关闭,即session关闭而无法读取到信息的问题 -->
	   <filter>  
            <filter-name>Spring OpenEntityManagerInViewFilter</filter-name>  
            <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>  
        </filter>  
        <filter-mapping>  
        <filter-name>Spring OpenEntityManagerInViewFilter</filter-name>  
            <url-pattern>/*</url-pattern>  
        </filter-mapping>    
          	     
       <filter>  
           <filter-name>shiroFilter</filter-name>  
           <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
           <init-param>  
           <!-- 该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理 -->  
               <param-name>targetFilterLifecycle</param-name>  
               <param-value>true</param-value>  
           </init-param>  
      </filter>  
      <filter-mapping>  
          <filter-name>shiroFilter</filter-name>  
          <url-pattern>/*</url-pattern>  
     </filter-mapping>
	   	    	   	    	    	    
	    <servlet>
	        <servlet-name>spring</servlet-name>
	        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	        <load-on-startup>1</load-on-startup>
	    </servlet>
	 
	    <servlet-mapping>
	        <servlet-name>spring</servlet-name>
	        <url-pattern>*.do</url-pattern>
	     </servlet-mapping>
  
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
 
  <error-page>  
        <error-code>403</error-code>  
        <location>/WEB-INF/view/error/403.jsp</location>  
    </error-page>  
    <error-page>  
        <error-code>404</error-code>  
        <location>/WEB-INF/view/error/404.jsp</location>  
    </error-page>  
    <error-page>  
        <error-code>405</error-code>  
        <location>/WEB-INF/view/error/405.jsp</location>  
    </error-page>  
    <error-page>  
        <error-code>500</error-code>  
        <location>/WEB-INF/view/error/500.jsp</location>  
    </error-page>  
</web-app>


这里有一个比较可能出问题的地方,就是解决session会话延迟的配置,那个一定要放在DispatcherServlet之上哦

下面我贴下applicationContext.xml的内容

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xmlns:cache="http://www.springframework.org/schema/cache"	
	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/aop http://www.springframework.org/schema/aop/spring-aop-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/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
			http://www.springframework.org/schema/data/repository
            http://www.springframework.org/schema/data/repository/spring-repository-1.6.xsd
            http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd">
    
    <context:annotation-config />
    <cache:annotation-driven cache-manager="cacheManager" />
    
    <!-- 自动扫描并注解 -->
    <context:component-scan base-package="com.dorm" />
    <!-- 加载hibenate.properties -->
    <context:property-placeholder location="classpath:/hibernate.properties" />
    
    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
        <!-- 基本属性 url、user、password --> 
        <property name="url" value="${dataSource.url}" />  
        <property name="username" value="${dataSource.username}" />  
        <property name="password" value="${dataSource.password}" /> 
        <property name="driverClassName" value="${dataSource.driverClassName}" />
    </bean>
    
    <!-- 配置jpa实体工厂的参数 -->
	 <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="persistenceProvider" ref="persistenceProvider" />
        <property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
        <property name="jpaDialect" ref="jpaDialect" />
        <property name="jpaProperties">
            <props>
               <prop key="hibernate.dialect">${dataSource.dialect}</prop>
			   <prop key="hibernate.hbm2ddl.auto">${dataSource.hbm2ddl.auto}</prop>
			   <!-- 避免重复打印sql -->
			   <prop key="hibernate.show_sql">${dataSource.show_sql}</prop>
			   <prop key="hibernate.format_sql">${dataSource.format_sql}</prop>
            </props>
        </property>        
        <property name="packagesToScan">
			<list>
				<value>com.dorm.entity</value>
		    </list>
		</property>	       
    </bean>
	
	<bean id="persistenceProvider"
        class="org.hibernate.ejb.HibernatePersistence" />
         
    <bean id="jpaVendorAdapter"
        class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
        <property name="database" value="MYSQL" />
    </bean>
     
    <bean id="jpaDialect"
        class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
        <!-- 配置jpa的路径 -->
    <jpa:repositories base-package="com.dorm.dao"
        entity-manager-factory-ref="entityManagerFactory" 
        transaction-manager-ref="txManager" />
        
    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
        p:cache-manager-ref="ehcache">
        </bean>    
        
    <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
        p:config-location="classpath:spring-ehcache.xml" />       
   

    <bean id="txManager"
        class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory"
            ref="entityManagerFactory" />
    </bean>
	
	<tx:annotation-driven transaction-manager="txManager" />
	    
		    
	<aop:config>
	<!-- 只对业务层进行开启事务  -->
		<aop:pointcut expression="execution(public * com.dorm.service.impl.*.*(..))"
			id="businessService" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="businessService" />
		
		<!-- aop面拦截,把拦截的堆栈信息的日志打印到日志文件当中 -->
		<aop:aspect id="aspect" ref="aspectBean">
		    <aop:pointcut expression="execution(public * com.dorm.controller.*.*(..))" id="businessService1"/>
		    <aop:before pointcut-ref="businessService1" method="doBefore"/>
		    <aop:after-throwing  pointcut-ref="businessService1" throwing="e" method="doAfterThrow" />    
            <aop:after pointcut-ref="businessService1" method="doAfter"/>    
            <aop:around pointcut-ref="businessService1" method="doAround"/>            
		</aop:aspect> 
		
	</aop:config> 
	
	<bean id="aspectBean" class="com.dorm.util.Aspect" />
	 <tx:advice id="txAdvice" transaction-manager="txManager">
		<tx:attributes>
		<!-- 配置哪些方法需要回滚  -->
		    <tx:method name="find*" read-only="true" propagation="NOT_SUPPORTED" />
            <tx:method name="delete*" propagation="REQUIRED" rollback-for="Exception" />
            <tx:method name="save*" propagation="REQUIRED" rollback-for="Exception" />
            <tx:method name="update*" propagation="REQUIRED" rollback-for="Exception" />        
                
		</tx:attributes>
	</tx:advice>
	<!-- 验证码的配置 -->	
	<bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">  
                <property name="config">  
                        <bean class="com.google.code.kaptcha.util.Config">  
                                <!--通过构造函数注入属性值 -->  
                                <constructor-arg type="java.util.Properties">  
                                        <props>  
                                            <!-- 验证码宽度 -->  
                                            <prop key="kaptcha.image.width">80</prop>   
                                            <!-- 验证码高度 -->  
                                            <prop key="kaptcha.image.height">30</prop>  
                                            <!-- 生成验证码内容范围 -->  
                                            <prop key="kaptcha.textproducer.char.string">0123456789</prop>  
                                            <!-- 验证码个数 -->  
                                            <prop key="kaptcha.textproducer.char.length">4</prop>  
                                            <!-- 是否有边框 -->  
                                            <prop key="kaptcha.border">yes</prop>  
                                            <!-- 边框颜色 -->  
                                            <prop key="kaptcha.border.color">black</prop>  
                                            <!-- 边框厚度 -->  
                                            <prop key="kaptcha.border.thickness">1</prop>  
                                            <!-- 验证码字体颜色 -->  
                                            <prop key="kaptcha.textproducer.font.color">black</prop>  
                                            <!-- 验证码字体大小 -->  
                                            <prop key="kaptcha.textproducer.font.size">25</prop>  
                                            <!-- 验证码所属字体样式 -->  
                                            <prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop>  
                                                 
                                            <prop key="kaptcha.noise.impl">com.google.code.kaptcha.impl.NoNoise</prop>  
                                            <!-- 干扰线颜色 -->
                                            <!--<prop key="kaptcha.noise.color">blue</prop>  
                                            --><!-- 验证码文本字符间距 -->  
                                            <prop key="kaptcha.textproducer.char.space">3</prop>
                                              
                                            <prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.NoWater</prop>  
                                           </props>  
                                </constructor-arg>  
                        </bean>  
                </property>  
         </bean>  
</beans>


东西比较多,大家有不明白的地方直接回复我。

当然下面是spring-servlet.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:p="http://www.springframework.org/schema/p"    
    xmlns:mvc="http://www.springframework.org/schema/mvc"    
    xmlns:context="http://www.springframework.org/schema/context"    
    xmlns:util="http://www.springframework.org/schema/util"   
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd    
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
    
    <mvc:annotation-driven />
    <!-- 解决不能拦截controller的代理问题 -->
    <aop:aspectj-autoproxy proxy-target-class="true" />
    
   <!-- 扫描此路径下类,自动注解 -->
   <context:component-scan base-package="com.dorm.controller" use-default-filters="false">
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
	</context:component-scan>    
     
 
     
     <!-- 开启注解式aop --><!--
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">
        <property name="proxyTargetClass" value="true" />
    </bean>
      
    --><bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">  
        <property name="securityManager" ref="securityManager"/>  
    </bean>
 
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>  
    
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
        <property name="exceptionMappings">
        <props>
              <prop key="org.apache.shiro.authz.UnauthorizedException">/error/error</prop>
        </props>
        </property>
    </bean> 
    
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
    
    <bean id="viewResolver"
	  class="org.springframework.web.servlet.view.UrlBasedViewResolver">
	  
	  <property name="viewClass"
	   value="org.springframework.web.servlet.view.JstlView" />
	   
	   <!-- 跳转页面的前缀和后缀文件名 -->
	  <property name="prefix" value="/WEB-INF/view/" />
	  <property name="suffix" value=".jsp" />
	  
	 </bean>
</beans>


这里面比较容易有问题的代理设置拦截controller,另外还有spring-shiro可能拦截不到的权限问题进行了处理。

下面就是对权限控制的配置spring-shiro.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:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
    http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util-3.0.xsd">
    
    <bean id="myRealm" class="com.dorm.util.MyRealm"/>
     
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
        <property name="realm" ref="myRealm"/>  
    </bean>
    
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>   
        <property name="loginUrl" value="/login.jsp"/>
       
        <property name="filterChainDefinitions">  
            <value>      
                /login.jsp=anon        
            </value>  
       </property>
    </bean>    
       
</beans>


对于权限的验证,在登录的控制时进行登入,在注解上进行验证。

下面就是页面代码内容:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>登录</title>
    
    <style type="text/css">
        .kaptcha{
            
        }
    </style>
     
    <script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
    <script type="text/javascript" src="js/jquery.min.js"></script></head>
  
    <script type="text/javascript">
                $(function (){  
                     $('#kaptcha').click(  
                        
                        function (){  
                            $(this).attr('src', 'kaptcha/kaptcha.do?' + Math.floor(Math.random() * 100));   
                         }  
                     );            
                 });      
     </script>
    

  <body>
       <form action="dorm/login.do">
         <label>姓名</label>
         <input type="text" name="userName" /><br>
         <label>密码</label>
         <input type="password" name="userPassword" />
         <img class="kaptcha" id="kaptcha" src="kaptcha/kaptcha.do"/><br>
         <input type="submit" value="登录" />     
     </form>
  </body>
</html>


只是一个简单的登录页面,字段要和实体类的字段名字匹配哦。

下面就是controller类:

登录处理类LoginController,我只是做了测试,只用的用户名登录,这点很抱歉哦

@Controller("loginController")
@RequestMapping("/dorm")
public class LoginController {
    
	private String LOGIN_SUCCESS="login/login_success";
	private String LOGIN_FAIL="login/login_fail";
	
	@Autowired
	private LoginService loginService;
	
	@RequestMapping("/login.do")
	public String login(User user,HttpServletRequest request) throws Exception{
		String code = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
		User u=loginService.findByName(user.getUserName());
		if(u!=null){
			
			UsernamePasswordToken token=new UsernamePasswordToken(user.getUserName(),user.getUserPassword());
			Subject subject=SecurityUtils.getSubject();
			subject.login(token);
			
			return LOGIN_SUCCESS;
		}
		return LOGIN_FAIL;
	}
}

需要说的实在使用权限的时候在方法的头部放上@RequestPermisson

KaptchaController验证码处理类:

@Controller("kaptchaController")
@RequestMapping("/kaptcha")
public class KaptchaController {
    
	@Autowired  
    private Producer captchaProducer;
	
	@RequestMapping("/kaptcha.do")
	public void initCaptcha(HttpServletRequest request,    
            HttpServletResponse response) throws Exception{  
          response.setDateHeader("Expires", 0);     
          response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");    
          response.addHeader("Cache-Control", "post-check=0, pre-check=0");    
          response.setHeader("Pragma", "no-cache");    
          response.setContentType("image/jpeg");    
          String capText = captchaProducer.createText();    
          request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);    
          BufferedImage bi = captchaProducer.createImage(capText);    
  
          ServletOutputStream out = response.getOutputStream();    
          ImageIO.write(bi, "jpg", out);    
            
          try{    
              out.flush();    
          }finally{    
              out.close();    
          }    
    }  
}

下面就是业务service层了

LoginService

public interface LoginService {
	
    public User findByName(String loginName);   
    
}


集成service.impl

@Service("loginSerivce")
public class LoginServiceImpl implements LoginService{
    
	@Resource
	private LoginDao loginDao; 
			
	public User findByName(String loginName) {
		
		User u=loginDao.findByUserName(loginName);
		//System.out.println(u+"uuuuuuuuuuu");		
		return u;
	}
	
}

jpa所在的持久层了哦

public interface LoginDao extends Repository<User, Integer>{
    
	public User findByUserName(String name);
    
	public void delete(Integer id);
			
}

接下来是实体了

User

@Entity
@Table(name="user")
public class User implements Serializable{

	
    private static final long serialVersionUID = 6177417450707400228L;
	
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="userid",nullable=false)
	private int userId;
    
	@Column(name="username")
	private String userName;
	
	@Column(name="userpassword")
    private String userPassword;
	
    /*
     * cascade:为级联操作,里面有级联保存,级联删除等,all为所有 
     * fetch:加载类型,有lazy和eager二种,
     *   eager为急加载,意为立即加载,在类加载时就加载,lazy为慢加载,第一次调用的时候再加载,由于数据量太大,onetomany一般为lazy
     * mappedBy:这个为manytoone中的对象名,这个不要变哦
     * 
     * <UserRole>:为要获得的mappedBy的类
     */
    @OneToMany(fetch=FetchType.LAZY,mappedBy="user",cascade=CascadeType.ALL)
	private List<UserRole> listUserRole; 
	
	public int getUserId() {
		return userId;
	}

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

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getUserPassword() {
		return userPassword;
	}

	public void setUserPassword(String userPassword) {
		this.userPassword = userPassword;
	}

	public List<UserRole> getListUserRole() {
		return listUserRole;
	}

	public void setListUserRole(List<UserRole> listUserRole) {
		this.listUserRole = listUserRole;
	}	
}


Role

package com.dorm.entity;

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


import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;



@Entity
@Table(name="role")
public class Role implements Serializable{
	
	
	private static final long serialVersionUID = 6177417450707400228L;   
	
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="roleid",nullable=false)
	private int roleId;
	
	@Column(name="rolename")
    private String roleName;
	
	@OneToMany(fetch=FetchType.LAZY,mappedBy="role",cascade=CascadeType.ALL)
	private List<UserRole> listUserRole;
	
	@OneToMany(fetch=FetchType.LAZY,mappedBy="role",cascade=CascadeType.ALL)
	private List<RolePermission> listRolePermission;
			
	public int getRoleId() {
		return roleId;
	}
	public void setRoleId(int roleId) {
		this.roleId = roleId;
	}
	
	public String getRoleName() {
		return roleName;
	}
	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}
	
	public List<UserRole> getListUserRole() {
		return listUserRole;
	}
	public void setListUserRole(List<UserRole> listUserRole) {
		this.listUserRole = listUserRole;
	}
	
	public List<RolePermission> getListRolePermission() {
		return listRolePermission;
	}
	public void setListRolePermission(List<RolePermission> listRolePermission) {
		this.listRolePermission = listRolePermission;
	}	
}


UserRole

package com.dorm.entity;

import java.io.Serializable;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="userrole")
public class UserRole implements Serializable{
    
	private static final long serialVersionUID = 6177417450707400228L;
	
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="id",nullable=false)
	private int id;
	
	@ManyToOne(fetch=FetchType.EAGER,cascade=CascadeType.ALL)
	@JoinColumn(name="userid")
	private User user;
	
    @ManyToOne(fetch=FetchType.EAGER,cascade=CascadeType.ALL)
	@JoinColumn(name="roleid")
	private Role role;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	
	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}
	
}


Permission

package com.dorm.entity;

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

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="permission")
public class Permission implements Serializable{
    
    private static final long serialVersionUID = 6177417450707400228L;
    
    @Id
	@GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="permissionid",nullable=false)
	private int permissionId;
	
    @Column(name="permission")
	private String permission;
    
	@OneToMany(fetch=FetchType.LAZY,mappedBy="permission",cascade=CascadeType.ALL)
	private List<RolePermission> listRolePermission;
    	
	public int getPermissionId() {
		return permissionId;
	}

	public void setPermissionId(int permissionId) {
		this.permissionId = permissionId;
	}

	public String getPermission() {
		return permission;
	}

	public void setPermission(String permission) {
		this.permission = permission;
	}

	public List<RolePermission> getListRolePermission() {
		return listRolePermission;
	}

	public void setListRolePermission(List<RolePermission> listRolePermission) {
		this.listRolePermission = listRolePermission;
	}
}

下面当然得是我们的aop拦截通知和shiro的权限

Aspect

public class Aspect {
	Logger logger = Logger.getLogger(Aspect.class);  
	String strLog = null ;  


	public void doBefore(JoinPoint jp) {  
		strLog = "log Begining method: "  
				+ jp.getTarget().getClass().getName() + "."  
				+ jp.getSignature().getName();  
		logger.warn(strLog);  
	}  

	public Object doAround(ProceedingJoinPoint pjp) throws Throwable {  
		long time = System.currentTimeMillis();  
		Object retVal = pjp.proceed();  
		time = System.currentTimeMillis() - time;  
		System.out.println("process time: " + time + " ms");  
		return retVal;  
	}  

	public void doAfter(JoinPoint jp) {  
		strLog ="doAfter:log Ending method: "  
				+ jp.getTarget().getClass().getName() + "."  
				+ jp.getSignature().getName();   
		logger.warn(strLog);  
	} 

	public void doAfterThrow(JoinPoint jp,Exception e){
		System.out.println("*****************异常信息如下**************");
		System.out.println("method " + jp.getTarget().getClass().getName()
				+ "." + jp.getSignature().getName() + " throw exception");

		StringWriter   sw=new   StringWriter();   			
		e.printStackTrace(new PrintWriter(sw));

		logger.error(sw.toString());
	}
}

MyRealm
 

public class MyRealm extends AuthorizingRealm{
	
    @Autowired
    private LoginService loginService;

	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String loginName = (String) principals.fromRealm(getName()).iterator().next();
        User user=loginService.findByName(loginName);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        List<String> permissionList=new ArrayList<String>();
    	if(user!=null){
    	    List<UserRole> listUserRole=user.getListUserRole();
    	    for(UserRole userRole:listUserRole){
    	    	Role role=userRole.getRole();
    	    	if(role!=null){
    	    		List<RolePermission> ListRolePermission=role.getListRolePermission();
        	    	for(RolePermission rolePermission:ListRolePermission){
        	    		permissionList.add(rolePermission.getPermission().getPermission());
        	    	}
    	    	}    	
    	    }  		
    		info.addStringPermissions(permissionList);
    		return info;
    	}
    	
        return null;  
	}


	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token=(UsernamePasswordToken)authcToken;
		User user=loginService.findByName(token.getUsername());
        
    	if(user!=null){
    		SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(user.getUserName(),user.getUserPassword(),getName());
    		return info;
    	}
        return null;  
	}

}



相关阅读 :
spring完整demo实例
spring快速入门实例教程
详解Spring中bean实例化的三种方式
Spring搭配Ehcache实例解析
Spring Bean基本管理实例详解
Spring中的事务管理实例详解
spring实例化javabean的三种方式分享
使用Spring的注解方式实现AOP实例
使用spring实现邮件的发送实例(含测试,源码,注释)
Spring AOP切面解决数据库读写分离实例详解
Spring AOP的实现原理详解及实例
Spring MVC的文件下载实例详解
最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务