SSM项目整合

1. spring配置文件application.xml

1.1 扫描包

交给SpringMVC处理

1.2 数据源

application.xml
value值可以通过PropertyPlaceholderConfigurer读取本地的配置文件获取,使用${username}方式;
此处暂且写死,未展示读取配置的方式。

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

	<!-- 数据源配置 (myBatis和Spring共用) -->
	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location">
			<!-- <value>classpath:database.properties</value> -->
			<value>file:E:/GSConf/conf/config.properties</value>
		</property>
	</bean>
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://localhost:3306/db_mis"></property>
		<property name="username" value="root"></property>
		<property name="password" value="root"></property>
	</bean>
</beans>

1.3 mybatis相关

application.xml

	<!-- myBatis测试时的利用sqlSessionFactory加载配置文件 -->
	<!-- 配置sqlSessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<!-- 批量起别名 -->
		<property name="typeAliasesPackage" value="cn.com.gs.ssm.libraryMIS.model"></property>
		<!-- 批量映射xml -->
		<property name="mapperLocations" value="classpath:cn/com/gs/ssm/libraryMIS/mapper/*.xml" ></property>
	</bean>
	<!-- 1.传统方式:配置sqlsession 产生这个实例就是通过 SqlSessionTemplate来实现的 -->
	<!-- <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> -->
		<!-- <constructor-arg index="0"><ref bean="sqlSessionFactory" /></constructor-arg> -->
	<!-- </bean> -->
	<!-- 2.Mapper代理:配置mapper扫描,自动生成dao实现类,生成的bean名字为Mapper接口类名,首字母小写 -->
	<bean id="mapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- 指定扫描包路径,即mapper接口包路径 -->
		<property name="basePackage" value="cn.com.gs.ssm.libraryMIS.dao" />
		<!-- 配置sqlSessionFactoryBeanName -->
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
		<!-- 配置sqlSessionFactory:会导致数据源配置不管用,数据库连接不上。且spring 4弃用-->
		<!-- <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> -->
	</bean>

1.4 声明式事务

application.xml

	<!-- 配置事务管理 -->
	<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
	<!-- 开启事务注解 -->
	<tx:annotation-driven transaction-manager="txManager" />
	<!-- 利用AOP,实现对Service的声明式事务管理 -->
	<!-- 通知 -->
	<tx:advice id="txAdvice" transaction-manager="txManager">
		<tx:attributes>
			<tx:method name="*" rollback-for="java.lang.Exception" />
		</tx:attributes>
	</tx:advice>

1.5 面向切面的日志

application.xml

	<!-- 注入切面 ,日志执行的方法-->
	<!-- 注入切点,使用注解注入 -->
	<bean id="logAspectBean" class="cn.com.gs.ssm.libraryMIS.aop.LogAspect" />	
	<aop:config>
		<!-- 指向切面 -->
		<aop:aspect id="logAspect" ref="logAspectBean">
			<!-- 切入点表达式 -->
			<aop:pointcut id="logPointcut" expression="execution(* cn.com.gs.ssm.libraryMIS.controller.*.*(..))"/>
			<!-- 在切入点周围要执行的方法,仅仅around支持ProceedingJoinPoint -->
			<aop:around pointcut-ref="logPointcut" method="doAround"/>
		</aop:aspect>
	</aop:config>

2. SpringMVC配置文件 spring-servlet.xml

2.1 扫描包

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:aop="http://www.springframework.org/schema/aop"
    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.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd ">
	
	<!-- 设置扫描包 -->
	<context:component-scan base-package="cn.com.gs.ssm.libraryMIS.*"/>
	<!-- 开启spring mvc的注解功能 -->
	<mvc:annotation-driven />
	
	<aop:aspectj-autoproxy />
</beans>

2.2 视图解析

spring-servlet.xml

<!--  视图解析器 -->  
    <bean id="viewResolver"  class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
	    <property name="prefix" value="/WEB-INF/jsp/"> </property>  
	    <property name="suffix"  value=".jsp"></property>  
    </bean>

2.3 拦截器

spring-servlet.xml

<!-- 登录拦截器 -->
	<mvc:interceptors>
		<mvc:interceptor>
			<mvc:mapping path="/user/*" />
			<mvc:exclude-mapping path="/user/login.do" />
			<bean class="cn.com.gs.ssm.libraryMIS.interceptor.SysUserInterceptor" />
		</mvc:interceptor>
	</mvc:interceptors>

3. mybatis配置

设置别名和xml映射,可使用xml配置,也可使用bean注入;
数据源配置已交由spring管理;

3.1 设置别名

3.1.1 方式一:单个起别名(不推荐)

缺点:每一个实体类都要手动配置;
SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<!-- 设置别名  用于resultType 存在的意义仅在于用来减少类完全限定名的冗余-->
	<typeAliases>
		<!-- 方式一:单个起别名 -->
		<typeAlias type="cn.com.gs.ssm.libraryMIS.model.User" alias="user"/>
		<typeAlias type="cn.com.gs.ssm.libraryMIS.model.Book" alias="book"/>
	</typeAliases>
</configuration>
3.1.2 方式二:批量起别名(推荐)

SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<!-- 设置别名  用于resultType 存在的意义仅在于用来减少类完全限定名的冗余-->
	<typeAliases>
		<!-- 方式二:批量起别名,扫描指定包下的所有类,扫描之后的别名就是类名(不区分大小写),建议使用的时候和类名一致--> 
		<package name="cn.com.gs.ssm.libraryMIS.model"/>
	</typeAliases>
</configuration>

application.xml
给SqlSessionFactoryBean配置configLocation属性值。

	<!-- myBatis测试时的利用sqlSessionFactory加载配置文件 -->
	<!-- 配置sqlSessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- mybatis配置文件路径 -->
		<property name="configLocation" value="classpath:config/SqlMapConfig.xml" />
		<property name="dataSource" ref="dataSource" />
	</bean>
	<!-- 1.传统方式:配置sqlsession 产生这个实例就是通过 SqlSessionTemplate来实现的 -->
	<!-- <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> -->
		<!-- <constructor-arg index="0"><ref bean="sqlSessionFactory" /></constructor-arg> -->
	<!-- </bean> -->
	<!-- 2.Mapper代理:配置mapper扫描,自动生成dao实现类,生成的bean名字为Mapper接口类名,首字母小写 -->
	<bean id="mapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- 指定扫描包路径,即mapper接口包路径 -->
		<property name="basePackage" value="cn.com.gs.ssm.libraryMIS.dao" />
		<!-- 配置sqlSessionFactoryBeanName -->
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
		<!-- 配置sqlSessionFactory:会导致数据源配置不管用,数据库连接不上。且spring 4弃用-->
		<!-- <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> -->
	</bean>
3.1.3 方式三:bean注入(推荐)

application.xml
给SqlSessionFactoryBean配置typeAliasesPackage属性值。

	<!-- myBatis测试时的利用sqlSessionFactory加载配置文件 -->
	<!-- 配置sqlSessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<!-- 批量起别名 -->
		<property name="typeAliasesPackage" value="cn.com.gs.ssm.libraryMIS.model"></property>
		<!-- 批量映射xml -->
		<property name="mapperLocations" value="classpath:cn/com/gs/ssm/libraryMIS/mapper/*.xml" ></property>
	</bean>
	<!-- 1.传统方式:配置sqlsession 产生这个实例就是通过 SqlSessionTemplate来实现的 -->
	<!-- <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> -->
		<!-- <constructor-arg index="0"><ref bean="sqlSessionFactory" /></constructor-arg> -->
	<!-- </bean> -->
	<!-- 2.Mapper代理:配置mapper扫描,自动生成dao实现类,生成的bean名字为Mapper接口类名,首字母小写 -->
	<bean id="mapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- 指定扫描包路径,即mapper接口包路径 -->
		<property name="basePackage" value="cn.com.gs.ssm.libraryMIS.dao" />
		<!-- 配置sqlSessionFactoryBeanName -->
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
		<!-- 配置sqlSessionFactory:会导致数据源配置不管用,数据库连接不上。且spring 4弃用-->
		<!-- <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> -->
	</bean>

3.2 映射xml

3.2.1 方式一:单个映射——resource
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>	
	<!-- 配置mapper映射文件 -->
	<mappers>
		<!-- 方式一:使用resouce,单个映射xml文件 -->
		<mapper resource="cn/com/gs/ssm/libraryMIS/mapper/UserMapper.xml"/>
		<mapper resource="cn/com/gs/ssm/libraryMIS/mapper/BookMapper.xml"/>
	</mappers>
</configuration>
3.2.2 单个映射——class
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>	
	<!-- 配置mapper映射文件 -->
	<mappers>
		<!-- 方式二:使用class,单个映射接口的xml 
			要求:遵循约定,xml与接口在一个包内,且同名
		-->
		<mapper class="cn.com.gs.ssm.libraryMIS.dao.book.BookDao"/>
	</mappers>
</configuration>
3.2.3 批量映射——package
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>	
	<!-- 配置mapper映射文件 -->
	<mappers>
		<!-- 方式三:package,使用接口所在包进行配置,批量映射接口的xml
			要求:遵循约定,xml与接口在一个包内,且同名
		 -->
		<package name="cn.com.gs.ssm.libraryMIS.dao"/>
	</mappers>
</configuration>
3.2.4 批量映射——bean注入

给SqlSessionFactoryBean配置mapperLocations属性值。代码如3.1.3所示。

3.3 数据源

已交由spring配置

3.4 mapper代理

指定mapper接口位置
application.xml

	<!-- 2.Mapper代理:配置mapper扫描,自动生成dao实现类,生成的bean名字为Mapper接口类名,首字母小写 -->
	<bean id="mapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- 指定扫描包路径,即mapper接口包路径 -->
		<property name="basePackage" value="cn.com.gs.ssm.libraryMIS.dao" />
		<!-- 配置sqlSessionFactoryBeanName -->
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
		<!-- 配置sqlSessionFactory:会导致数据源配置不管用,数据库连接不上。且spring 4弃用-->
		<!-- <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> -->
	</bean>

4. web.xml

4.1 spring监听

<?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"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>libraryMIS</display-name>
	
	<!-- spring监听:项目启动就会监听到,执行config/applicationContext-*.xml -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:config/applicationContext-*.xml</param-value>
	</context-param>
</web-app>	

4.2 过滤器

	<!-- 字符集过滤 -->
	<filter>
		<filter-name>encodingFilter</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>encodingFilter</filter-name>
		<url-pattern>*.do</url-pattern>
	</filter-mapping>
	
	<!-- 自定义session过滤器-->
	<filter>
		<filter-name>SessionFilter</filter-name>
		<filter-class>cn.com.gs.ssm.libraryMIS.filter.SessionFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>SessionFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

4.3 SpringMVC请求拦截

	<!-- springMVC配置 -->
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:config/spring-servlet.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>

5.整合shiro

5.1 application-shiro.xml

5.1.1 DefaultWebSecurityManager

给DefaultWebSecurityManager指定realm,指向自己定义的处理器;

<?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:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	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.2.xsd  
                http://www.springframework.org/schema/context  
                http://www.springframework.org/schema/context/spring-context-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/aop
                http://www.springframework.org/schema/aop/spring-aop-3.2.xsd ">
	
	<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<property name="realm" ref="sysUserRealm"></property>
		<!--配置缓存-->
		<property name="cacheManager" ref="ehcacheManager"/>
	</bean>
</beans>
5.1.2 SysUserRealm
<bean id="sysUserRealm" class="cn.com.gs.ssm.libraryMIS.realm.SysUserRealm"></bean>
5.1.3 EhCacheManager
	<!-- ehcache缓存:shiro默认集成了ehcache的简单配置文件,若要自定义请放于src下 -->
	<bean id="ehcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
		<property name="cacheManagerConfigFile" value="classpath:config/ehcache.xml" ></property>
	</bean>
5.1.4 ShiroFilterFactoryBean
	<!-- 注入shiro过滤器 -->
	<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
		<!-- 1.配置securityManager,是一个对象所以用ref引用 -->
		<property name="securityManager" ref="securityManager"></property>
		<!-- 2.配置loginUrl,当访问需要认证的资源时,若果没有认证,则跳转到该页面;如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面 -->
		<property name="loginUrl" value="/sysUser/toLogin.do"></property>
		<!-- 3.配置successUrl,当认证成功后,就跳转至该页面。通常不设置,若不设置,认证成功后会跳转到上一个url -->
		<property name="successUrl" value="/sysUser/toMain.do"></property>
		<!-- 4.配置unauthorizedUrl,没有权限访问时,跳转至该页面(很容易出现问题:直接异常出错,并不跳转!!!) 
			解决办法:在spring-mvc的配置文件中注入org.springframework.web.servlet.handler.SimpleMappingExceptionResolver
				指定一个exception的Properties对象
			<property name="unauthorizedUrl" value="/sysUser/toRefuse.do"></property>
		-->
		
		<!-- 5.配置filterChainDefinitions过滤器链,anon=匿名访问,authc=需要认证 -->
		<property name="filterChainDefinitions">
			<value>
				/sysUser/toLogin.do=anon
				/sysUser/toShiroLogin.do=anon
				/sysUser/login.do=anon
				/sysUser/timeout.do=anon
				/sysUser/toRefuse.do=anon
				/static/**=anon
				/2/**=anon
				/bootstrap/**=anon
				/css/**=anon
				/Hui-iconfont/**=anon
				/images/**=anon
				/img/**=anon
				/js/**=anon
				/**=authc
			</value>
		</property>
	</bean>

5.2 SysUserRealm.java

package cn.com.gs.ssm.libraryMIS.realm;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.permission.PermissionResolver;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import cn.com.gs.common.util.StringUtil;
import cn.com.gs.ssm.libraryMIS.dao.ButtonDao;
import cn.com.gs.ssm.libraryMIS.dao.MenuDao;
import cn.com.gs.ssm.libraryMIS.dao.RoleDao;
import cn.com.gs.ssm.libraryMIS.dao.sysUser.UserDao;
import cn.com.gs.ssm.libraryMIS.model.Button;
import cn.com.gs.ssm.libraryMIS.model.Menu;
import cn.com.gs.ssm.libraryMIS.model.Role;
import cn.com.gs.ssm.libraryMIS.model.User;

public class SysUserRealm extends AuthorizingRealm{
	@Resource
	private UserDao userDao;
	@Resource
	private RoleDao roleDao;
	@Resource
	private MenuDao menuDao;
	@Resource
	private ButtonDao buttonDao;
	
	protected String getRealmName(){
		return "sysUserRealm";
	}
	
	/**
	 * 认证
	 * 
	 * */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("------认证:doGetAuthenticationInfo--------");
		//1.从token中获取用户输入的用户名
		String account = token.getPrincipal().toString();
		System.out.println("输入的账户名:"+account);
		//2.根据用户名去查询数据库,得到账密信息(要求用户名唯一)
		User user = userDao.getUserByAccount(account);
		if(user == null){
			return null;
		}
		/*
		 * 3.将信息封装给SimpleAuthenticationInfo:
		 * Object principal, 	身份信息:可以传入查询出的对象,也可以只传入用户名(传入对象subject就可以获取到)
		 * Object credentials, 	密码信息:传入数据库查询出的密码信息
		 * String realmName		Realm的名字
		 * 
		 * shiro内部将会比对token的密码和传入的数据库密码是否相等,返回SimpleAuthenticationInfo对象
		 * Subject就会得到该SimpleAuthenticationInfo信息,
		 * 最后在controller的登录方法里,由subject判断是否认证通过
		 * 		通过:获取对象存入session
		 * */
		//TODO 密码加密的情况,学习盐值
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), getRealmName());
		return info;
	}


	/**
	 * 授权
	 * 前台发请求,先走shiro的过滤器链(包含自定义过滤器)
	 * 前台进入页面后,每个被shiro标记的按钮都会发请求来验证权限,效率很低
	 * 请整合redis缓存
	 * 
	 * */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
		Integer menuId = null;
		Integer buttonId = null;
		Menu menu = null;
		Button button = null;
		System.out.println("-----------授权方法------------");
		//1.获取已登录的个人身份信息(认证时传入SimpleAuthenticationInfo的个人信息)
		User user = (User)principal.getPrimaryPrincipal();
		
		//TODO 已集成ehcache 学习整合Redis,先查缓存,缓存中没有再查数据库
		
		//2.获取该用户的已授权按钮信息(菜单级别暂时用NetSeal的写法)
		Role role = roleDao.getRoleById(user.getRoleId());
		//TODO 已实现按钮用shiro标签的实现,基于url的暂未实现
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		//3.将菜单的code信息(shiro要求的授权规则)传给SimpleAuthorizationInfo
		String menuIds = role.getMenuId();
		String[] menuIdArr = menuIds.split(",");
		for(String tempId : menuIdArr){
			tempId = tempId.trim();
			menuId = Integer.parseInt(tempId);
			menu = menuDao.getMenuById(menuId);
			if(StringUtil.isNotBlank(menu.getMenuCode())) {
				info.addStringPermission(menu.getMenuCode());
			}
			//添加url,在自定义过滤器中控制访问
			info.addStringPermission(menu.getUrl());
		}
		//4.将按钮的code信息(shiro要求的授权规则)传给SimpleAuthorizationInfo
		String buttonIds = role.getButtonId();
		String[] buttonIdArr = buttonIds.split(",");
		for(String tempId : buttonIdArr){
			tempId = tempId.trim();
			buttonId = Integer.parseInt(tempId);
			button = buttonDao.getButtonById(buttonId);
			info.addStringPermission(button.getButtonCode());
		}
		//添加url,在自定义过滤器中控制访问
		info.addStringPermission(button.getUrl());
		return info;
	}

}

5.3 web.xml

	<!-- shiro过滤器:由spring-web的DelegatingFilterProxy代理来实现-->
	<filter>
		<filter-name>shiroFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
		<init-param>
			<!-- 表示bean的生命周期由servlet来管理 -->
			<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>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SSM项目整合Shiro的步骤如下: 1. 引入Shiro的依赖,可以在pom.xml文件中添加以下代码: ```xml <!--shiro--> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.9.0</version> </dependency> ``` 2. 在Spring配置文件中配置Shiro的相关信息,例如Shiro的安全管理器、Shiro的过滤器链等。可以在applicationContext.xml文件中添加以下代码: ```xml <!-- 配置Shiro的安全管理器 --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="myRealm"/> </bean> <!-- 配置Shiro的自定义Realm --> <bean id="myRealm" class="com.example.shirodemo.realm.MyRealm"> <property name="credentialsMatcher" ref="hashedCredentialsMatcher"/> </bean> <!-- 配置Shiro的密码匹配器 --> <bean id="hashedCredentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"> <property name="hashAlgorithmName" value="md5"/> <property name="hashIterations" value="2"/> </bean> <!-- 配置Shiro的过滤器链 --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager"/> <property name="loginUrl" value="/login"/> <property name="successUrl" value="/index"/> <property name="unauthorizedUrl" value="/unauthorized"/> <property name="filterChainDefinitions"> <value> /login = anon /logout = logout /** = authc </value> </property> </bean> ``` 3. 创建自定义Realm,继承org.apache.shiro.realm.Realm接口,并实现其中的方法。可以创建一个MyRealm类,代码如下: ```java public class MyRealm implements Realm { @Autowired private UserService userService; @Override public String getName() { return "myRealm"; } @Override public boolean supports(AuthenticationToken token) { return token instanceof UsernamePasswordToken; } @Override public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { String username = (String) token.getPrincipal(); String password = new String((char[]) token.getCredentials()); User user = userService.getUserByUsername(username); if (user == null) { throw new UnknownAccountException("用户名或密码错误!"); } if (!password.equals(user.getPassword())) { throw new IncorrectCredentialsException("用户名或密码错误!"); } SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName()); return info; } } ``` 4. 在Controller中使用Shiro进行权限控制。可以在UserController中添加以下代码: ```java @Controller public class UserController { @RequestMapping("/user/list") @RequiresPermissions("user:list") public String list() { return "user/list"; } @RequestMapping("/user/add") @RequiresPermissions("user:add") public String add() { return "user/add"; } @RequestMapping("/user/edit") @RequiresPermissions("user:edit") public String edit() { return "user/edit"; } @RequestMapping("/user/delete") @RequiresPermissions("user:delete") public String delete() { return "user/delete"; } } ``` 以上是SSM项目整合Shiro的基本步骤,可以根据具体需求进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值