黄色网址大全免费-黄色网址你懂得-黄色网址你懂的-黄色网址有那些-免费超爽视频-免费大片黄国产在线观看

專注Java教育14年 全國咨詢/投訴熱線:400-8080-105
動力節點LOGO圖
始于2009,口口相傳的Java黃埔軍校
首頁 hot資訊 常見的Shiro異常處理方案

常見的Shiro異常處理方案

更新時間:2022-05-27 09:32:45 來源:動力節點 瀏覽2299次

@Override
    public int saveObject(SysUser entity, Integer[] roleIds) {
        // 1.參數合法驗證
        if (entity == null)
            throw new IllegalArgumentException("保存對應不能為空");
        if (StringUtils.isEmpty(entity.getUsername()))
            throw new ServiceException("用戶名不能為空");
        if (StringUtils.isEmpty(entity.getPassword()))
            throw new ServiceException("密碼不能為空");
        if (roleIds == null || roleIds.length == 0)
            throw new IllegalArgumentException("必須為用戶分配角色");
        // 2.保存數據
        // 2.1 創建一個鹽值(用于輔助加密,保證密碼更加安全的一種手段)
        String salt = UUID.randomUUID().toString();
        System.out.println(salt);
        String pwd = entity.getPassword();
        // 2.3 對密碼進行加密,加密算法md5
        SimpleHash sh = // 這個api屬于shiro框架,后續需要引入shiro依賴
                new SimpleHash("MD5", // algorithmName 表示加密算法
                        pwd, // source 為要加密的對象
                        salt);// salt 加密鹽值
        entity.setPassword(sh.toHex());
        System.out.println(salt);
        entity.setSalt(salt);
        // 2.4設置對象其它屬性默認值
        entity.setCreatedTime(new Date());
        entity.setModifiedTime(new Date());
        // 2.5保存用戶自身信息
        int rows = sysUserDao.insertObject(entity);
        // 2.6保存用戶與角色的關系數據
        sysUserRoleDao.insertObjects(entity.getId(), roleIds);
        // 3.返回結果
        return rows;
    }

方案一:只處理一種異常,其他異常拋出

@Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("==doGetAuthenticationInfo===");
        // 獲取用戶身份信息(如用戶名)
        String userName = (String) token.getPrincipal();
        // 1.從token對象獲取用戶名(用戶輸入的)
        // 基于用戶名訪問數據庫獲取用戶信息
        SysUser user = sysUserDao.findUserByUserName(userName);
        // 對用戶信息進行驗證
        // 2.基于用戶名查詢用戶信息并進行身份校驗
        if (user == null)// 驗證用戶名是否為空
            throw new AuthenticationException("此用戶不存在");
        if (user.getValid() == 0)// 驗證用戶是否被禁用
            throw new AuthenticationException("此用戶已被禁用");
        // 3.對用戶信息進行封裝(基于業務封裝用戶數據)
        ByteSource credentialsSalt = ByteSource.Util.bytes(user.getSalt());
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, // principal
                                                                            // 用戶->身份
                user.getPassword(), // hashedCredentials已加密的憑證
                credentialsSalt, // credentialsSalt 密碼加密時使用的鹽
                this.getName());// realmName 當前方法所在類的名字
        return info;// 返回給誰?認證管理器
    }
@ExceptionHandler(IncorrectCredentialsException.class)
    @ResponseBody
    public JsonResult doHandleShiroException(IncorrectCredentialsException e){
        JsonResult result=new JsonResult();
        result.setState(0);
        result.setMessage("密碼不正確");
        return result;
        
    }

方案二:處理多種異常,ShiroException作為異常的父類

@Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("==doGetAuthenticationInfo===");
        // 獲取用戶身份信息(如用戶名)
        String userName = (String) token.getPrincipal();
        // 1.從token對象獲取用戶名(用戶輸入的)
        // 基于用戶名訪問數據庫獲取用戶信息
        SysUser user = sysUserDao.findUserByUserName(userName);
        // 對用戶信息進行驗證
        // 2.基于用戶名查詢用戶信息并進行身份校驗
        if (user == null)// 驗證用戶名是否為空
            throw new UnknownAccountException();
        if (user.getValid() == 0)// 驗證用戶是否被禁用
            throw new LockedAccountException();
        // 3.對用戶信息進行封裝(基于業務封裝用戶數據)
        ByteSource credentialsSalt = ByteSource.Util.bytes(user.getSalt());
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, // principal
                                                                            // 用戶->身份
                user.getPassword(), // hashedCredentials已加密的憑證
                credentialsSalt, // credentialsSalt 密碼加密時使用的鹽
                this.getName());// realmName 當前方法所在類的名字
        return info;// 返回給誰?認證管理器
    }
@ExceptionHandler(ShiroException.class)
    @ResponseBody
    public JsonResult doHandleShiroException(ShiroException e){
        JsonResult result=new JsonResult();
        result.setState(0);
        if(e instanceof IncorrectCredentialsException)
        result.setMessage("密碼不正確");
        else if(e instanceof UnknownAccountException)
            result.setMessage("此賬戶不存在");
        else if(e instanceof LockedAccountException)
            result.setMessage("賬戶已被禁用");
        return result;
        
    }

方案二:完整代碼

package com.jt.service.realm;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
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 org.springframework.stereotype.Service;
import com.jt.dao.SysUserDao;
import com.jt.entity.SysUser;
/**
 * 此對象中要完成用戶認證信息,授權信息的獲取和封裝等業務操作
 * 
 * @author Administrator
 *
 */
@Service
public class ShiroUserRealm extends AuthorizingRealm {
    @Autowired
    private SysUserDao sysUserDao;
    /**
     * 設置憑證(Credentials)匹配器
     * 指定加密算法和加密次數,默認加密一次
     */
    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        HashedCredentialsMatcher cMatcher = new HashedCredentialsMatcher("MD5");
        // 設置加密的次數(這個次數應該與保存密碼時那個加密次數一致)
        // cMatcher.setHashIterations(5);
        super.setCredentialsMatcher(cMatcher);
    }
    /**
     * 負責用戶認證信息的獲取及封裝
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("==doGetAuthenticationInfo===");
        // 獲取用戶身份信息(如用戶名)
        String userName = (String) token.getPrincipal();
        // 1.從token對象獲取用戶名(用戶輸入的)
        // 基于用戶名訪問數據庫獲取用戶信息
        SysUser user = sysUserDao.findUserByUserName(userName);
        // 對用戶信息進行驗證
        // 2.基于用戶名查詢用戶信息并進行身份校驗
        if (user == null)// 驗證用戶名是否為空
            throw new UnknownAccountException();
        if (user.getValid() == 0)// 驗證用戶是否被禁用
            throw new LockedAccountException();
        // 3.對用戶信息進行封裝(基于業務封裝用戶數據)
        ByteSource credentialsSalt = ByteSource.Util.bytes(user.getSalt());
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, // principal
                                                                            // 用戶->身份
                user.getPassword(), // hashedCredentials已加密的憑證
                credentialsSalt, // credentialsSalt 密碼加密時使用的鹽
                this.getName());// realmName 當前方法所在類的名字
        return info;// 返回給誰?認證管理器
    }
    /**
     * 負責用戶授權信息的獲取及封裝
     * */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
        PrincipalCollection principals) {
            return null;        
    }
}
package com.jt.common.web;
import java.util.logging.Logger;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import com.jt.common.vo.JsonResult;
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 處理運行時異常
     * @return
     */
    //jdk中自帶的日志api
    private Logger log=Logger.getLogger(GlobalExceptionHandler.class.getName());
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public JsonResult doHandleRuntimeException(RuntimeException e){
        /**
         * 封裝異常信息
         */
        //e.printStackTrace();
        log.info(e.getMessage());
        return new JsonResult(e);
    }
    @ExceptionHandler(ShiroException.class)
    @ResponseBody
    public JsonResult doHandleShiroException(ShiroException e){
        JsonResult result=new JsonResult();
        result.setState(0);
        if(e instanceof IncorrectCredentialsException)
        result.setMessage("密碼不正確");
        else if(e instanceof UnknownAccountException)
            result.setMessage("此賬戶不存在");
        else if(e instanceof LockedAccountException)
            result.setMessage("賬戶已被禁用");
        return result;        
    }
}
package com.jt.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.jt.common.vo.SysUserDeptResult;
import com.jt.entity.SysUser;
public interface SysUserDao {    
    /**
     * 更新用戶信息
     * @param entity
     * @return
     */
    int updateObject(SysUser entity);
    /**
     * 根據用戶id查詢用戶以及用戶對應的部門信息
     * @param id (用戶id)
     * @return
     */
    SysUserDeptResult findObjectById(Integer id);
    /**
     * 
     * @param deptId 部門id
     * @return
     */
    int getUserCountByDeptId(Integer deptId);    
    /**
     * 根據用戶名查找用戶信息
     * @param username
     * @return
     */
     SysUser findUserByUserName(String username);    
     /**
      * 負責將用戶信息寫入到數據庫
      * @param entity
      * @return
      */
     int insertObject(SysUser entity);    
     /**
      * 賦值執行禁用和啟用操作
      * @param id 要禁用或啟用的記錄id
      * @param valid 禁用或啟用的標識
      * @return
      */
     int validById(@Param("id")Integer id,
                   @Param("valid")Integer valid,
                   @Param("modifiedUser") String modifiedUser);
    /**
     * 依據條件分頁查詢操作
     * @param username
     * @param startIndex
     * @param pageSize
     * @return
     */
     List<SysUserDeptResult> findPageObjects(
             @Param("username")String username,
             @Param("startIndex")Integer startIndex,
             @Param("pageSize")Integer pageSize);     
     /**
      * 依據條件統計記錄總數
      * @param username
      * @return
      */
     int getRowCount(@Param("username")String username);
}
<select id="findUserByUserName" resultType="com.jt.entity.SysUser">
select *
from sys_users
where username=#{username}
</select>
<?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.jt.dao.SysUserDao">

    <!-- 更新用戶自身信息 -->

    <update id="updateObject" parameterType="com.jt.entity.SysUser">
        update sys_users
        <set>
            <if test="username!=null and username!=''">
                username=#{username},
            </if>
            <if test="email!=null and email!=''">
                email=#{email},
            </if>
            <if test="mobile!=null and mobile!=''">
                mobile=#{mobile},
            </if>
            <if test="deptId!=null and deptId!=''">
                deptId=#{deptId},
            </if>
            <if test="modifiedUser!=null and modifiedUser!=''">
                modifiedUser=#{modifiedUser},
            </if>
            modifiedTime=now()
        </set>
        where id=#{id}
    </update>
    <select id="findObjectById" resultMap="sysUserResult">
        select *
        from sys_users
        where id=#{id}
    </select>
    <!-- 基于用戶名查詢當前用戶對象 -->
    <select id="findUserByUserName" resultType="com.jt.entity.SysUser">
        select *
        from sys_users
        where username=#{username}
    </select>
    <insert id="insertObject" parameterType="com.jt.entity.SysUser"
        useGeneratedKeys="true" keyProperty="id">
        insert into sys_users
        (username,password,salt,email,mobile,valid,deptId,
        createdTime,modifiedTime,createdUser,modifiedUser)
        values
        (#{username},#{password},#{salt},
        #{email},#{mobile},#{valid},#{deptId},
        now(),now(),#{createdUser},#{modifiedUser}
        )
    </insert>
    <!-- 禁用或啟用用戶對象 -->
    <update id="validById">
        update sys_users
        set
        valid=#{valid},
        modifiedTime=now(),
        modifiedUser=#{modifiedUser}
        where id=#{id}
    </update>
    <resultMap id="sysUserResult" type="com.jt.common.vo.SysUserDeptResult">
        <!--直接量類型的屬性自動映射-->
        <!--關聯映射-->
        <association property="sysDept" column="deptId"
            select="com.jt.dao.SysDeptDao.findById" />
    </resultMap>
    <select id="getUserCountByDeptId" resultType="int">
        select count(*)
        from sys_users
        where deptId=#{deptId}
    </select> 
    <sql id="queryWhereId">
        <where>
            <if test="username!=null and username!=''">
                username like concat("%",#{username},"%")
            </if>
        </where>
    </sql>
    <select id="findPageObjects" resultMap="sysUserResult">
        select *
        from sys_users
        <include refid="queryWhereId" />
        limit #{startIndex},#{pageSize}
    </select>
    <select id="getRowCount" resultType="int">
        select count(*)
        from sys_users
        <include refid="queryWhereId" />
    </select>
</mapper>

 

提交申請后,顧問老師會電話與您溝通安排學習

免費課程推薦 >>
技術文檔推薦 >>
主站蜘蛛池模板: 嫩模被xxxx视频在线观看 | 琪琪色在线视频 | 一级特黄aaa大片免费看 | 97视频免费观看 | 1717she永久精品免费 | 成年网站免费 | 黄频大全 | 亚洲精品videosexhd| www.黄色在线观看 | 一级毛片一级毛片一级毛片aa | 久久综合免费视频 | 亚洲大香伊人蕉在人依线 | 男人搞女人视频 | 亚洲小视频在线观看 | 欧美日韩国产网站 | 欧美一级特黄啪啪片免费看 | 日韩久久中文字幕 | 色播在线永久免费视频 | 国产成人影院在线观看 | 成人免费视频软件网站 | 深夜福利日韩 | 天天操夜夜夜 | 久久精品国产亚洲高清 | 老司机亚洲精品影院 | 影音先锋在线亚洲精品推荐 | 99久久精品国产一区二区 | 成人亚洲欧美日韩中文字幕 | 国产精品视频a | 亚久久伊人精品青青草原2020 | 日韩三级大片 | 手机在线看片国产 | 国产无套粉嫩白浆在线精品 | 波少野结衣色在线 | 在线观看黄p免费 | 欧美不卡精品中文字幕日韩 | 欧美亚洲国产日韩 | 99视频全部免费 | 添人人躁日日躁夜夜躁夜夜揉 | 国产精品合集一区二区三区 | 免费一级黄 | 污视频网站免费观看 |