目录
首先看一下数据库表

- package com.ssr.ssm.mapper;
-
- import com.ssr.ssm.model.User;
- import org.springframework.stereotype.Repository;
-
- import java.util.Set;
-
- @Repository
- public interface UserMapper {
- int deleteByPrimaryKey(Integer userid);
-
- int insert(User record);
-
- int insertSelective(User record);
-
- User selectByPrimaryKey(Integer userid);
-
- User queryByName(String userName);
-
- int updateByPrimaryKeySelective(User record);
-
- int updateByPrimaryKey(User record);
-
- Set
getRolesByUserId(String userName); -
- Set
getPersByUserId(String userName); - }
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
- <mapper namespace="com.ssr.ssm.mapper.UserMapper" >
- <resultMap id="BaseResultMap" type="com.ssr.ssm.model.User" >
- <constructor >
- <idArg column="userid" jdbcType="INTEGER" javaType="java.lang.Integer" />
- <arg column="username" jdbcType="VARCHAR" javaType="java.lang.String" />
- <arg column="password" jdbcType="VARCHAR" javaType="java.lang.String" />
- <arg column="salt" jdbcType="VARCHAR" javaType="java.lang.String" />
- <arg column="createdate" jdbcType="TIMESTAMP" javaType="java.util.Date" />
- </constructor>
- </resultMap>
- <sql id="Base_Column_List" >
- userid, username, password, salt, createdate
- </sql>
- <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
- select
- <include refid="Base_Column_List" />
- from t_shiro_user
- where userid = #{userid,jdbcType=INTEGER}
- </select>
- <select id="queryByName" resultType="com.ssr.ssm.model.User" parameterType="java.lang.String">
- select
- <include refid="Base_Column_List" />
- from t_shiro_user
- where userName = #{userName}
- </select>
-
- <select id="getRolesByUserId" resultType="java.lang.String" parameterType="java.lang.String">
- select ur.roleid from t_shiro_user u,t_shiro_user_role ur,t_shiro_role r
- where u.userid = ur.userid and ur.roleid = r.roleid
- and u.username = #{username}
- </select>
- <select id="getPersByUserId" resultType="java.lang.String" parameterType="java.lang.String">
- select rp.perid from t_shiro_user u,t_shiro_user_role ur,t_shiro_role_permission rp,t_shiro_permission p
- where u.userid = ur.userid and ur.roleid = rp.roleid and rp.perid = p.perid
- and u.username = #{username}
- </select>
-
-
- <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
- delete from t_shiro_user
- where userid = #{userid,jdbcType=INTEGER}
- </delete>
- <insert id="insert" parameterType="com.ssr.ssm.model.User" >
- insert into t_shiro_user (userid, username, password,
- salt, createdate)
- values (#{userid,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
- #{salt,jdbcType=VARCHAR}, #{createdate,jdbcType=TIMESTAMP})
- </insert>
- <insert id="insertSelective" parameterType="com.ssr.ssm.model.User" >
- insert into t_shiro_user
- <trim prefix="(" suffix=")" suffixOverrides="," >
- <if test="userid != null" >
- userid,
- </if>
- <if test="username != null" >
- username,
- </if>
- <if test="password != null" >
- password,
- </if>
- <if test="salt != null" >
- salt,
- </if>
- <if test="createdate != null" >
- createdate,
- </if>
- </trim>
- <trim prefix="values (" suffix=")" suffixOverrides="," >
- <if test="userid != null" >
- #{userid,jdbcType=INTEGER},
- </if>
- <if test="username != null" >
- #{username,jdbcType=VARCHAR},
- </if>
- <if test="password != null" >
- #{password,jdbcType=VARCHAR},
- </if>
- <if test="salt != null" >
- #{salt,jdbcType=VARCHAR},
- </if>
- <if test="createdate != null" >
- #{createdate,jdbcType=TIMESTAMP},
- </if>
- </trim>
- </insert>
- <update id="updateByPrimaryKeySelective" parameterType="com.ssr.ssm.model.User" >
- update t_shiro_user
- <set >
- <if test="username != null" >
- username = #{username,jdbcType=VARCHAR},
- </if>
- <if test="password != null" >
- password = #{password,jdbcType=VARCHAR},
- </if>
- <if test="salt != null" >
- salt = #{salt,jdbcType=VARCHAR},
- </if>
- <if test="createdate != null" >
- createdate = #{createdate,jdbcType=TIMESTAMP},
- </if>
- </set>
- where userid = #{userid,jdbcType=INTEGER}
- </update>
- <update id="updateByPrimaryKey" parameterType="com.ssr.ssm.model.User" >
- update t_shiro_user
- set username = #{username,jdbcType=VARCHAR},
- password = #{password,jdbcType=VARCHAR},
- salt = #{salt,jdbcType=VARCHAR},
- createdate = #{createdate,jdbcType=TIMESTAMP}
- where userid = #{userid,jdbcType=INTEGER}
- </update>
- </mapper>
- package com.ssr.ssm.biz;
-
- import com.ssr.ssm.model.User;
-
- import java.util.Set;
-
- /**
- * @author ssr
- * @create 2022-08-25 18:06
- */
- public interface UserBiz {
- int deleteByPrimaryKey(Integer userid);
-
- int insert(User record);
-
- int insertSelective(User record);
-
- User selectByPrimaryKey(Integer userid);
-
- User queryByName(String userName);
-
- int updateByPrimaryKeySelective(User record);
-
- int updateByPrimaryKey(User record);
-
- Set
getRolesByUserId(String userName); -
- Set
getPersByUserId(String userName); -
- }
-
- package com.ssr.ssm.biz.impl;
-
- import com.ssr.ssm.biz.UserBiz;
- import com.ssr.ssm.mapper.UserMapper;
- import com.ssr.ssm.model.User;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
-
- import java.util.Set;
-
- /**
- * @author ssr
- * @create 2022-08-25 18:08
- */
- @Service("UserService")
- public class UserBizImpl implements UserBiz {
- @Autowired
- private UserMapper userMapper;
-
- @Override
- public int deleteByPrimaryKey(Integer userid) {
- return userMapper.deleteByPrimaryKey(userid);
- }
-
- @Override
- public int insert(User record) {
- return userMapper.insert(record);
- }
-
- @Override
- public int insertSelective(User record) {
- return userMapper.insertSelective(record);
- }
-
- @Override
- public User selectByPrimaryKey(Integer userid) {
- return userMapper.selectByPrimaryKey(userid);
- }
-
- @Override
- public User queryByName(String userName) {
- return userMapper.queryByName(userName);
- }
-
- @Override
- public int updateByPrimaryKeySelective(User record) {
- return userMapper.updateByPrimaryKeySelective(record);
- }
-
- @Override
- public int updateByPrimaryKey(User record) {
- return userMapper.updateByPrimaryKey(record);
- }
-
- @Override
- public Set<String> getRolesByUserId(String userName) {
- return userMapper.getRolesByUserId(userName);
- }
-
- @Override
- public Set<String> getPersByUserId(String userName) {
- return userMapper.getPersByUserId(userName);
- }
- }
-
- "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.xsd">
-
-
- <bean id="shiroRealm" class="com.ssr.ssm.shiro.Myrealm">
- <property name="userBiz" ref="UserService" />
-
-
-
-
- <property name="credentialsMatcher">
- <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
-
- <property name="hashAlgorithmName" value="md5"/>
-
- <property name="hashIterations" value="1024"/>
-
- <property name="storedCredentialsHexEncoded" value="true"/>
- bean>
- property>
- bean>
-
-
- <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
- <property name="realm" ref="shiroRealm" />
- bean>
-
-
- <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
-
- <property name="securityManager" ref="securityManager" />
-
- <property name="loginUrl" value="/login"/>
-
-
-
- <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
-
- <property name="filterChainDefinitions">
- <value>
-
-
-
-
- /user/login=anon
- /user/updatePwd.jsp=authc
- /admin/*.jsp=roles[4]
- /user/teacher.jsp=perms[2]
-
- value>
- property>
- bean>
-
-
- <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
- beans>
- package com.ssr.ssm.shiro;
-
- import com.ssr.ssm.biz.UserBiz;
- import com.ssr.ssm.model.User;
- 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.realm.AuthorizingRealm;
- import org.apache.shiro.subject.PrincipalCollection;
- import org.apache.shiro.util.ByteSource;
-
- import java.util.Set;
-
- /**
- * @author ssr
- * @create 2022-08-25 18:16
- */
- public class Myrealm extends AuthorizingRealm {
- private UserBiz userBiz;
-
- public UserBiz getUserBiz() {
- return userBiz;
- }
-
- public void setUserBiz(UserBiz userBiz) {
- this.userBiz = userBiz;
- }
-
- @Override
- protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
- System.out.println("用户授权...");
- String username = principals.getPrimaryPrincipal().toString();
- User user = userBiz.queryByName(username);
- Set
roles = userBiz.getRolesByUserId(user.getUsername()); - Set
pers = userBiz.getPersByUserId(user.getUsername()); - SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
- info.setRoles(roles);
- info.setStringPermissions(pers);
- return info;
- }
-
- @Override
- protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
- System.out.println("身份验证...");
- String username = token.getPrincipal().toString();
- String password = token.getCredentials().toString();
- User user = userBiz.queryByName(username);
- AuthenticationInfo info=new SimpleAuthenticationInfo(
- user.getUsername(),
- user.getPassword(),
- ByteSource.Util.bytes(user.getSalt()),
- this.getName()
- );
- return info;
- }
- }
-


- <?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:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="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-4.3.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.xsd">
- <!-- 通过context:component-scan元素扫描指定包下的控制器-->
- <!--1) 扫描com.javaxl.zf及子子孙孙包下的控制器(扫描范围过大,耗时)-->
- <aop:aspectj-autoproxy/>
- <context:component-scan base-package="com.ssr.ssm"/>
-
- <!--2) 此标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->
- <!--两个bean,这两个bean是spring MVC为@Controllers分发请求所必须的。并提供了数据绑定支持,-->
- <!--@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)-->
- <mvc:annotation-driven></mvc:annotation-driven>
-
- <!--3) ViewResolver -->
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar -->
- <property name="viewClass"
- value="org.springframework.web.servlet.view.JstlView"></property>
- <property name="prefix" value="/"/>
- <property name="suffix" value=".jsp"/>
- </bean>
-
- <!--4) 单独处理图片、样式、js等资源 -->
- <!--<mvc:resources location="/css/" mapping="/css/**"/>-->
- <!--<mvc:resources location="/images/" mapping="/images/**"/>-->
- <!--<mvc:resources location="/js/" mapping="/js/**"/>-->
- <mvc:resources location="/static/" mapping="/js/**"/>
-
- <!--文件上传:多功能解析器-->
- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
- <!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 -->
- <property name="defaultEncoding" value="UTF-8"></property>
- <!-- 文件最大大小(字节) 1024*1024*50=50M-->
- <property name="maxUploadSize" value="52428800"></property>
- <!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
- <property name="resolveLazily" value="true"/>
- </bean>
-
- <!--配置拦截器-->
- <!--<mvc:interceptors>
- <!–针对于所有的请求进行拦截–>
- <bean class="com.ssr.ssm.intercept.OneHandlerInterceptor"></bean>
- </mvc:interceptors>-->
- <!--配置拦截器链-->
- <!-- <mvc:interceptors>
- <mvc:interceptor>
- <mvc:mapping path="/**"/>
- <bean class="com.ssr.ssm.intercept.OneHandlerInterceptor"></bean>
- </mvc:interceptor>
- <mvc:interceptor>
- <mvc:mapping path="/clz/**"/>
- <bean class="com.ssr.ssm.intercept.TwoHandlerInterceptor"></bean>
- </mvc:interceptor>
- </mvc:interceptors>-->
-
- <!--支持json数据返回的适配器-->
- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
- <property name="messageConverters">
- <list>
- <ref bean="mappingJackson2HttpMessageConverter"/>
- </list>
- </property>
- </bean>
- <bean id="mappingJackson2HttpMessageConverter"
- class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
- <!-- 处理中文乱码以及避免IE执行AJAX时,返回JSON出现下载文件-->
- <property name="supportedMediaTypes">
- <list>
- <value>text/html;charset=UTF-8</value>
- <value>text/json;charset=UTF-8</value>
- <value>application/json;charset=UTF-8</value>
- </list>
- </property>
- </bean>
-
- <!--统一异常处理-->
- <!-- springmvc提供的简单异常处理器 -->
- <!--<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
- <!– 定义默认的异常处理页面 –>
- <property name="defaultErrorView" value="error"/>
- <!– 定义异常处理页面用来获取异常信息的变量名,也可不定义,默认名为exception –>
- <property name="exceptionAttribute" value="ex"/>
- <!– 定义需要特殊处理的异常,这是重要点 –>
- <property name="exceptionMappings">
- <props>
- <prop key="java.lang.RuntimeException">error</prop>
- </props>
- <!– 还可以定义其他的自定义异常 –>
- </property>
- </bean>-->
-
- <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
- depends-on="lifecycleBeanPostProcessor">
- <property name="proxyTargetClass" value="true"></property>
- </bean>
- <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
- <property name="securityManager" ref="securityManager"/>
- </bean>
-
- <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
- <property name="exceptionMappings">
- <props>
- <prop key="org.apache.shiro.authz.UnauthorizedException">
- unauthorized
- </prop>
- </props>
- </property>
- <property name="defaultErrorView" value="unauthorized"/>
- </bean>
-
-
- </beans>
-
-
- package com.ssr.ssm.web;
-
- import org.apache.shiro.authz.annotation.Logical;
- import org.apache.shiro.authz.annotation.RequiresPermissions;
- import org.apache.shiro.authz.annotation.RequiresRoles;
- import org.apache.shiro.authz.annotation.RequiresUser;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
-
- import javax.servlet.http.HttpServletRequest;
-
- /**
- * @author ssr
- * @create 2022-08-26 19:18
- */
- @RequestMapping("/shiro")
- @Controller
- public class ShiroController {
-
- @RequiresUser
- @RequestMapping("/passUser")
- public String passUser(HttpServletRequest request){
- System.out.println("身份认证通过..");
- return "admin/addUser";
- }
-
- @RequiresRoles(value = {"1","4"},logical = Logical.AND)
- @RequestMapping("/passRole")
- public String passRole(HttpServletRequest request){
- System.out.println("角色认证通过..");
- return "admin/addUser";
- }
-
- @RequiresPermissions(value = {"2"},logical = Logical.AND)
- @RequestMapping("/passPermission")
- public String permission(HttpServletRequest request){
- System.out.println("权限认证通过..");
- return "admin/addUser";
- }
- }
-
