Spring+SpringMVC+Mybatis+Shiro 入门

mac2022-06-30  17

Spring+SpringMVC+Mybatis+Shiro

1.配置文件

pom.xml

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zzgs</groupId> <artifactId>Shiro05</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>Shiro05 Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <!-- 自定义版本号 --> <spring.version>4.3.8.RELEASE</spring.version> <!--Shiro 版本号 --> <shiro.version>1.3.2</shiro.version> <!-- mybatis.jar --> <mybatis.version>3.4.6</mybatis.version> <mybatis.spring.version>1.3.0</mybatis.spring.version> <!-- mysql --> <mysql.version>5.1.42</mysql.version> <druid.version>1.1.10</druid.version> <!--solr j --> <solrj.version>7.1.0</solrj.version> <!-- 其它依赖jar --> <jackson.version>2.8.8</jackson.version> <lombok.version>1.16.20</lombok.version> <jstl.version>1.2</jstl.version> <jstl.standard.version>1.1.2</jstl.standard.version> <log4j.version>1.2.17</log4j.version> <cglib.nodep.version>3.1</cglib.nodep.version> <commons.fileupload.version>1.3.1</commons.fileupload.version> <github.pagehelper.version>5.1.10</github.pagehelper.version> <ehcache.version>2.10.2</ehcache.version> </properties> <dependencies> <!-- Spring jar --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.8.0</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.0</version> </dependency> <!-- SpringMVC文件上传.jar --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${commons.fileupload.version}</version> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis.spring.version}</version> </dependency> <!-- mybatis 支持延迟加载 cglib-nodep --> <dependency> <groupId>cglib</groupId> <artifactId>cglib-nodep</artifactId> <version>${cglib.nodep.version}</version> </dependency> <!-- Mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!-- druid连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <!-- jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <!--JSTL标签 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>${jstl.standard.version}</version> </dependency> <!-- lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> <scope>provided</scope> </dependency> <!-- log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <!-- 日志需要 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.21</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.21</version> </dependency> <!-- mybatis 分页插件 pagehelper --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>${github.pagehelper.version}</version> </dependency> <!-- shiro需要的jar <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-all</artifactId> <version>1.3.2</version> </dependency> --> <!-- shiro需要的jar --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>${shiro.version}</version> </dependency> <!-- shiro spring --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>${shiro.version}</version> </dependency> <!-- shiro enchche 缓存 --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>${shiro.version}</version> </dependency> <!-- shiro需要的jar --> <!-- log4j 解决方案 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.15</version> <exclusions> <exclusion> <groupId>com.sun.jmx</groupId> <artifactId>jmxri</artifactId> </exclusion> <exclusion> <groupId>com.sun.jdmk</groupId> <artifactId>jmxtools</artifactId> </exclusion> <exclusion> <groupId>javax.jms</groupId> <artifactId>jms</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.6.1</version> </dependency> <!-- shiro需要的jar --> <!--Encache 缓存 --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.10.2</version> </dependency> <!--Encache 缓存 --> <dependency> <groupId>org.apache.solr</groupId> <artifactId>solr-solrj</artifactId> <version>${solrj.version}</version> </dependency> </dependencies> </project>

web.xml

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>Archetype Created Web Application</display-name> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:spring_*.xml</param-value> </context-param> <!-- SpringMVC编码格式处理UTF-8 --> <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> <!-- Shiro Filter is defined in the spring application context: --> <filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <init-param> <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> <!-- SpringMVC --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置 DispatcherServlet :DispatcherServlet 默认加载 /WEB-INF/<servletName-servlet>.xml 的 Spring 配置文件, 启动 WEB 层 的 Spring 容器。 可以通过 contextConfigLocation 初始化参数自定 义配置文件的位置和名称 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring_mvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <!-- / 拦截所有的请求,不包括JSP。 /* 拦截所有的请求(包括JSP) --> <url-pattern>/</url-pattern> </servlet-mapping> <!-- rest 配置 浏览器 form 表单只支持 GET 与 POST 请求,而DELETE、PUT 等 method 并不支 持, Spring3.0 添加了一个过滤器**HiddenHttpMethodFilter**,可以将这些请求转换 为标准的 http 方法,使得支持 GET、POST、PUT 与 DELETE 请求。 --> <filter> <filter-name>hiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>hiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>

springmvc.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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 仅扫描controller --> <context:component-scan base-package="com.zzgs" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 处理静态资源 将在 SpringMVC 上下文中定义一个 DefaultServletHttpRequestHandler, 它会对进入 DispatcherServlet 的 请求进行筛查, 如果发现是没有经过映射的请求,就将该请求交由 WEB 应用服务器默认的 Servlet 处理, 如果不是静态资源的请求,才由 DispatcherServlet 继续处理 --> <mvc:default-servlet-handler/> <!-- 是告知Spring,启用注解驱动。然后Spring会自动为我们注册上面说到多个Bean到工厂中,来处理我们的请求。 第一个是HandlerMapping的实现类,它会处理@RequestMapping 注解,并将其注册到请求映射表中。 ​ 第二个是HandlerAdapter的实现类,它是处理请求的适配器,就是确定调用哪个类的哪个方法,并且构造方法参数,返回值。 支持使用 **@RequestBody 和 @ResponseBody 注解** --> <mvc:annotation-driven/> </beans>

spring_core.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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <!--1 Spring IOC 指定扫描的包 @Service..@Repository @Component...--> <context:component-scan base-package="com.zzgs" > <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--2 Spring AOP启动配置 自动激活动态代理 @Aspect @Before @PointCut... <aop:aspectj-autoproxy ></aop:aspectj-autoproxy> --> <!-- 加载外部配置文件 property 标签中有一个属性location,用于指定属性文件的位置 --> <context:property-placeholder location="classpath:jdbc.properties"/> <!--3 配置数据源 druid --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${jdbc_driver}" /> <property name="url" value="${jdbc_url}" /> <property name="username" value="${jdbc_user}" /> <property name="password" value="${jdbc_password}" /> <!-- 配置初始化大小、最小、最大 --> <property name="initialSize" value="1" /> <property name="minIdle" value="1" /> <property name="maxActive" value="10" /> <!-- 配置获取连接等待超时的时间 --> <property name="maxWait" value="10000" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="300000" /> <property name="testWhileIdle" value="true" /> <!-- 这里建议配置为TRUE,防止取到的连接不可用 --> <property name="testOnBorrow" value="true" /> <property name="testOnReturn" value="false" /> <!-- 打开PSCache,并且指定每个连接上PSCache的大小 --> <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> <!-- 这里配置提交方式,默认就是TRUE,可以不用配置 --> <property name="defaultAutoCommit" value="true" /> <!-- 验证连接有效与否的SQL,不同的数据配置不同 --> <property name="validationQuery" value="select 1 " /> <!-- 配置监控统计拦截的filters --> <property name="filters" value="stat" /> </bean> <!--配置SqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> </bean> <!--配置Dao接口所在的包--> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.zzgs.dao"/> </bean> <!--配置声明式事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!--配置事务通知--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="find*" read-only="true"/> <tx:method name="*" isolation="DEFAULT"/> </tx:attributes> </tx:advice> <!--配置AOP增强--> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.zzgs.services.Impl.*ServiceImpl.*(..))*/"></aop:advisor> </aop:config> </beans>

jdbc.properties

jdbc_url=jdbc:mysql://localhost:3306/shiro_action jdbc_driver=com.mysql.jdbc.Driver jdbc_user=root jdbc_password=root

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" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- Shiro核心组件 --> <!-- 1 配置 securityManager--> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <!-- 配置缓存配置 --> <property name="cacheManager" ref="cacheManager"/> <property name="realm" ref="jdbcRealm"/> </bean> <!-- 2配置 缓存框架 ehcache--> <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> <property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/> </bean> <!-- 3 自定义Realm --> <bean id="jdbcRealm" class="com.zzgs.shiro.ShiroRealm"> <property name="credentialsMatcher"> <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"> <!--加密的名称--> <property name="hashAlgorithmName" value="MD5"/> <!--加密的次数--> <property name="hashIterations" value="10"></property> </bean> </property> </bean> <!-- <property name="credentialsMatcher"> <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"> <property name="hashAlgorithmName" value="SHA-256"/> </bean> </property> --> <!-- ========================================================= Shiro Spring特有的整合 ========================================================= --> <!-- 后处理器自动为Spring配置的Shiro对象调用init()和destroy()方法, 因此您不必1)为每个bean定义指定init-method和destroy-method属性, 2)甚至知道哪些Shiro对象要求调用这些方法。 Spring 自动管理Shiro的对象(生命周期管理) --> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> <!-- 为Spring配置的bean启用Shiro Annotations。仅在lifecycleBeanProcessor运行后运行 --> <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> <property name="securityManager" ref="securityManager"/> </bean> <!-- 前提条件: bean id 必须要和 web.xml shiroFilter一致 --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager"/> <!--未认证可以访问的页面 --> <property name="loginUrl" value="/login.jsp"/> <!-- 认证成功后可以访问的页面--> <property name="successUrl" value="/main.jsp"/> <!-- 无权限页面--> <property name="unauthorizedUrl" value="/unauth.jsp"/> <!-- <property name="filters"> <util:map> <entry key="aName" value-ref="someFilterPojo"/> </util:map> </property> --> <!-- map key=value 请求的URL资源=拦截器 anon 匿名拦截器 (未认证的情况下允许访问) authc 认证拦截器 (认证成功的情识下允许访问) logout 认证过滤器 roles[角色名称] 角色过滤器 Ant风格 通配符 说明 ? 匹配任何单字符 * 匹配0或者任意数量的字符 ** 匹配0或者更多的目录 优先顺序: 先声明 为优先。 --> <!--<property name="filterChainDefinitions"> <value> /login.jsp = anon /user/login=anon /css/**=anon /images/**=anon /js/**=anon /login/exit = logout /student.jsp=roles[stu] /teacher.jsp=roles[tea] /list.jsp=roles[stu,tea] /** = authc </value> </property>--> <property name="filterChainDefinitionMap" ref="filterChainDefinitionMap"></property> </bean> <!--工厂方法注入--> <!-- 1 构建Bean管理交由Spring ioc容器--> <bean id="filterChainDefinitionMapBuilder" class="com.zzgs.shiro.FilterChainDefinitionMapBuilder"></bean> <!-- 2 工厂方法注入--> <bean id="filterChainDefinitionMap" factory-bean="filterChainDefinitionMapBuilder" factory-method="builder" /> </beans>

ehcache.xml

<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false"> <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU" /> <!-- 这里的 users 缓存空间是为了下面的 demo 做准备 --> <cache name="users" eternal="false" maxElementsInMemory="100" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0" timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU" /> </ehcache>

shiro配置类

ShiroRealm.class 必须继承AuthorizingRealm

package com.zzgs.shiro; import com.zzgs.domain.User; import com.zzgs.services.UserServices; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.crypto.hash.SimpleHash; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.util.ByteSource; import org.springframework.beans.factory.annotation.Autowired; import java.util.HashSet; import java.util.Set; public class ShiroRealm extends AuthorizingRealm { @Autowired private UserServices userServices; /** * 认证 * @param authenticationToken * @return * @throws AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { //得到用户名 UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken; String username = upToken.getUsername(); User user = userServices.findByUserName(username); //判断用户是否在数据库中存在 if (user == null) { //如果用户名不存在 抛出UnknownAccountException throw new UnknownAccountException("用户名不存在"); } //如果用户名存在 状态处于被锁定 抛出LockedAccountException Status = 0 if (user.getStatus()==0){ throw new LockedAccountException("账户被锁定"); } //密码的比较 是shiro内部进行比较 Object principal = username; Object credentials = user.getPassword(); //数据库中查询出的密码 //盐值加密 ByteSource credentialsSalt = ByteSource.Util.bytes(username); //AuthenticationInfo info = new SimpleAuthenticationInfo(principal,credentials,super.getName()); AuthenticationInfo info = new SimpleAuthenticationInfo(principal,credentials,credentialsSalt,super.getName()); //如果用户名存在但是密码错误 底层会抛出 抛出IncorrectCredentialsException return info; } /** * 授权 * @param principalCollection * @return */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { //得到用户名信息 String username = (String) principalCollection.getPrimaryPrincipal(); //给当前的用户赋予相应的角色 Set<String> roles = userServices.findRoleByUserName(username); if(roles.contains("admin")){ //管理员是特殊角色 roles = userServices.findRoles(); } AuthorizationInfo info = new SimpleAuthorizationInfo(roles); return info; } }

FilterChainDefinitionMapBuilder类

package com.zzgs.shiro; import com.zzgs.domain.Resources; import com.zzgs.services.ResourcesServices; import org.springframework.beans.factory.annotation.Autowired; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class FilterChainDefinitionMapBuilder { @Autowired private ResourcesServices resourcesServices; public Map<String,String> builder(){ Map<String,String> map = new LinkedHashMap<String, String>(); List<Resources> resources = resourcesServices.selectAllAndStatusAndSortnum(); for (Resources resource : resources) { map.put(resource.getKey(),resource.getValue()); } return map; } }

数据库表

user表

idusernamepasswordnamestatusremark用户id用户名用户密码用户姓名激活状态备注信息 CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(50) DEFAULT NULL COMMENT '用户名', `password` varchar(50) DEFAULT NULL COMMENT '密码', `name` varchar(50) DEFAULT NULL COMMENT '姓名', `status` smallint(6) DEFAULT NULL COMMENT '激活状态', `remark` varchar(200) DEFAULT NULL COMMENT '注释', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8

role表

idrnameremarkstatus角色id角色名角色备注信息角色激活状态 CREATE TABLE `role` ( `id` int(11) NOT NULL AUTO_INCREMENT, `rname` varchar(20) DEFAULT NULL, `remark` varchar(20) DEFAULT NULL, `status` smallint(6) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8

user_role表

iduidridstatus主键id用户id角色id是否激活 CREATE TABLE `user_role` ( `id` int(11) NOT NULL AUTO_INCREMENT, `uid` int(11) DEFAULT NULL, `rid` int(11) DEFAULT NULL, `status` smallint(6) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8

resources表

idkeyvaluesortnumstatus资源id资源路径访问权限优先级激活状态 CREATE TABLE `resources` ( `id` int(11) NOT NULL AUTO_INCREMENT, `key` varchar(20) DEFAULT NULL, `value` varchar(20) DEFAULT NULL, `sortnum` int(11) DEFAULT NULL, `status` smallint(6) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8

实体类

User.class

@Data public class User implements Serializable { private Integer id; private String username; private String password; private String name; private short status; private String remark; }

Resources.clss

@Data public class Resources implements Serializable { private Integer id; private String key; private String value; private Integer sortnum; private Short status; }

Dao类中三表查询语句

public interface UsersDao { @Select("select * from user where username = #{username}") public User findByUserName(String username); //根据用户名查询所有的用户信息 @Select("SELECT role.rname FROM role WHERE role.id =(" + "SELECT user_role.rid FROM user_role WHERE user_role.uid =(" + "SELECT user.id FROM USER WHERE user.username = #{username}))") Set<String> findRoleByUserName(String username); @Select("select rname from role where status = 1") Set<String> findRoles(); }

GitHub链接地址

最新回复(0)