开发者社区> 问答> 正文

集成shiro 出现org.hibernate.HibernateExcepti?报错

在Realm中,
方法doGetAuthenticationInfo登录校验,通过sysUserService查询,执行正常
方法doGetAuthorizationInfo获取权限,也是通过sysUserService查询,结果会报错:org.hibernate.HibernateException: No Session found for current thread
同个类中,为什么一个正常,一个会报session找不到

请各位大侠帮忙指点!

web.xml:

<filter>
    <filter-name>shiroFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>shiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <filter>



applicationContext-shiro.xml:

<bean id="securityManager" 
   class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> 
   <property name="realm" ref="myRealm"/> 
   <property name="cacheManager" ref="shiroCacheManager" />
 </bean> 

 <bean id="myRealm" class="com.bkbk.module.admin.Realm.MyRealm"> 
 	<property name="sysUserService" ref="sysUserService"/>
 </bean>
 
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> 
   <property name="securityManager" ref="securityManager"/> 
   <property name="loginUrl" value="/admin/sys_user!login.action"/> 
   <property name="successUrl" value="/admin/process_definition!findPage.action"/> 
   <property name="unauthorizedUrl" value="/403.do"/> 
	<property name="filters">
		<map>
			<entry key="authenticationFilter" value-ref="authenticationFilter" />
		</map>
	</property>
   <property name="filterChainDefinitions"> 
 			<value>
				/admin/logout.jsp = logout
				/admin/work!** = perms["admin:work"]
			</value>
   </property> 
 </bean> 

	<bean id="shiroCacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
		<property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
	</bean>

	<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
	
	<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>



MyRealm.java:

public class MyRealm extends AuthorizingRealm implements  
Realm,   
InitializingBean{  
	
	
	private SysUserService sysUserService;

	
	public MyRealm() {
		super();

	}
	
 
    /** 
     * 认证信息 
     */  
	@Override
    protected AuthenticationInfo doGetAuthenticationInfo(  
                AuthenticationToken authcToken ) throws AuthenticationException {  
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;  
        String userName = token.getUsername();  
        if( userName != null && !"".equals(userName) ){  、
//这个地方查询,执行正常
        	SysUser user = sysUserService.login(token.getUsername(),  String.valueOf(token.getPassword()));
        	
            if( user != null )  
                return new SimpleAuthenticationInfo(  
                            user.getUserName(),user.getPassword(), getName());  
        }  
        return null;  
    }

	   /** 
     * 授权信息 
     */  
	@Override
    protected AuthorizationInfo doGetAuthorizationInfo(  
                PrincipalCollection principals) {  
      
        String username = SecurityUtils.getSubject().getPrincipals().fromRealm(getName()).toString();
        
      	
        if( username != null ){  
                SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();  
//这个地方去查询,结果在dao会报错:org.hibernate.HibernateException: No Session found for current thread
                info.addRoles(sysUserService.findRoleByUser(user));
                return info;  
            }  
        return null;  
    }  
  
	
	public SysUserService getSysUserService() {
		return sysUserService;
	}

	public void setSysUserService(SysUserService sysUserService) {
		this.sysUserService = sysUserService;
	}


	@Override
	public void afterPropertiesSet() throws Exception {
		 Assert.notNull(sysUserService);  
		// TODO Auto-generated method stub
		
	}
	

	@Override
	public String getName() {
		return getClass().getName();
	}

  
}



SysUserService.java:

public SysUser login(String userName, String password) {
		
		SysUser user = null;
		List<Object[]> list = sessionFactory.getCurrentSession().createSQLQuery("select id_,password_,user_name_ from `user_` where `user_name_`= '"+userName+"' and `password_`='"+password+"'").list();
		for(Object[] o : list)
		{
			user = new SysUser();
			user.setId(((BigInteger)o[0]).longValue());
			user.setPassword((String)o[1]);
			user.setUserName((String)o[2]);
		}
		return user;
	}

	public List<String> findResourceByUser(SysUser user) {
		
		return sessionFactory.getCurrentSession().createSQLQuery("select distinct(url_) from resource_").list();
	}





展开
收起
爱吃鱼的程序员 2020-06-22 12:54:54 433 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    spring配置事务了吗?有集成spring事务,spring版本是3.2<preclass="brush:xml;toolbar:true;auto-links:false;"><tx:annotation-drivenproxy-target-class="true"transaction-manager="transactionManager"/><beanid="transactionManager"class="org.springframework.orm.hibernate4.HibernateTransactionManager"><propertyname="sessionFactory"ref="sessionFactory"/></bean><tx:adviceid="transactionAdvice"transaction-manager="transactionManager"><tx:attributes><tx:methodname="save*"propagation="REQUIRED"/><tx:methodname="delete*"propagation="REQUIRED"/><tx:methodname="update*"propagation="REQUIRED"/><tx:methodname="get*"read-only="true"/><tx:methodname="load*"read-only="true"/><tx:methodname="find*"read-only="true"/><tx:methodname=""read-only="true"/></tx:attributes></tx:advice>

    这是事务的配置


    你用的hibernate是几?

    这个也需要配置:

    <preclass="brush:xml;toolbar:true;auto-links:false;"><aop:configproxy-target-class="true"><aop:advisoradvice-ref="txAdvice"pointcut="execution(com.名字.项目名称...(..))"/></aop:config>



    hibernate版本是4.1.2,有配置以下内容<aop:config><aop:advisorpointcut="execution( com.bkbk.service... (..))"advice-ref="transactionAdvice"/></aop:config>

    web.xml里有这个吗

    <preclass="brush:xml;toolbar:true;auto-links:false;"><filter><filter-name>openSessionInViewFilter</filter-name><filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class><init-param><param-name>singleSession</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>openSessionInViewFilter</filter-name><url-pattern>/</url-pattern></filter-mapping>



    有这个配置你DAO层里用的是getCurrentSession吗?是的

    老哥解决了吗

    2020-06-22 12:55:09
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
阿里邮箱—安全高效集成 立即下载
集成智能接入网关APP:优化企业级移动办公网络 立即下载
云效助力企业集成安全到DevOps中 立即下载