最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

springboot+thymeleaf+shiro標(biāo)簽的實(shí)例

 更新時(shí)間:2022年01月25日 10:46:15   作者:占星安啦  
這篇文章主要介紹了springboot+thymeleaf+shiro標(biāo)簽的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

1、pom中加入依賴(lài)

	<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
			<version>1.5.6.RELEASE</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf -->
		<dependency>
			<groupId>org.thymeleaf</groupId>
			<artifactId>thymeleaf</artifactId>
			<version>${thymeleaf.version}</version>
		</dependency>
        <!-- shiro安全框架 -->
		<dependency>
			<groupId>org.apache.shiro</groupId>
			<artifactId>shiro-spring</artifactId>
			<version>1.4.0</version>
		</dependency>
		<!--thymeleaf-shiro-extras-->
		<dependency>
			<groupId>com.github.theborakompanioni</groupId>
			<artifactId>thymeleaf-extras-shiro</artifactId>
			<version>1.2.1</version>
		</dependency>

2、用戶(hù)-角色-權(quán)限的表關(guān)系

//用戶(hù)表
public class User {
    private Integer userId;
    private String userName;
    private Set<Role> roles = new HashSet<>();
}
//角色表
public class User {
    private Integer id;
    private String role;
    private Set<Module> modules = new HashSet<>();
    private Set<User> users = new HashSet<>();
}
//權(quán)限表
public class Module {
    private Integer mid;
    private String mname;
    private Set<Role> roles = new HashSet<>();
}
    
    
//用戶(hù)查詢(xún)
<resultMap id="BaseResultMap" type="com.lanyu.common.model.User" >
    <id column="user_id" property="userId" jdbcType="INTEGER" />
    <result column="user_name" property="userName" jdbcType="VARCHAR" />
    <!-- 多對(duì)多關(guān)聯(lián)映射:collection -->
    <collection property="roles" ofType="Role">
      <id property="id" column="c_id" />
      <result property="role" column="role" />
      <collection property="modules" ofType="Module">
        <id property="mid" column="mid"/>
        <result property="mname" column="mname"/>
      </collection>
    </collection>
  </resultMap>
  
//查詢(xún)用戶(hù)信息,返回結(jié)果會(huì)自動(dòng)分組,得到用戶(hù)信息
  <select id="selectByPhone" resultMap="BaseResultMap" parameterType="java.lang.String" >
    SELECT
	  u.*, r.*, m.*
    FROM
        sys_user u
    INNER JOIN sys_user_role ur ON ur.userId = u.user_id
    INNER JOIN sys_role r ON r.rid = ur.roleid
    INNER JOIN sys_role_module mr ON mr.rid = r.rid
    INNER JOIN sys_module m ON mr.mid = m.mid
    WHERE
	  u.user_name=#{username} or u.phone=#{username};
  </select>

3、編寫(xiě)shiro核心類(lèi)

@Configuration
public class ShiroConfiguration {
    
    //用于thymeleaf模板使用shiro標(biāo)簽
    @Bean
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }
    @Bean(name="shiroFilter")
    public ShiroFilterFactoryBean shiroFilter(@Qualifier("securityManager") SecurityManager manager) {
        ShiroFilterFactoryBean bean=new ShiroFilterFactoryBean();
        bean.setSecurityManager(manager);
        //配置登錄的url和登錄成功的url
        bean.setLoginUrl("/loginpage");
        bean.setSuccessUrl("/indexpage");
        //配置訪(fǎng)問(wèn)權(quán)限
        LinkedHashMap<String, String> filterChainDefinitionMap=new LinkedHashMap<>();
//        filterChainDefinitionMap.put("/loginpage*", "anon"); //表示可以匿名訪(fǎng)問(wèn)
        filterChainDefinitionMap.put("/admin/*", "authc");//表示需要認(rèn)證才可以訪(fǎng)問(wèn)
        filterChainDefinitionMap.put("/logout*","anon");
        filterChainDefinitionMap.put("/img/**","anon");
        filterChainDefinitionMap.put("/js/**","anon");
        filterChainDefinitionMap.put("/css/**","anon");
        filterChainDefinitionMap.put("/fomts/**","anon");
        filterChainDefinitionMap.put("/**", "anon");
        bean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return bean;
    }
    //配置核心安全事務(wù)管理器
    @Bean(name="securityManager")
    public SecurityManager securityManager(@Qualifier("authRealm") AuthRealm authRealm) {
        System.err.println("--------------shiro已經(jīng)加載----------------");
        DefaultWebSecurityManager manager=new DefaultWebSecurityManager();
        manager.setRealm(authRealm);
        return manager;
    }
    //配置自定義的權(quán)限登錄器
    @Bean(name="authRealm")
    public AuthRealm authRealm(@Qualifier("credentialsMatcher") CredentialsMatcher matcher) {
        AuthRealm authRealm=new AuthRealm();
        authRealm.setCredentialsMatcher(matcher);
        return authRealm;
    }
    //配置自定義的密碼比較器
    @Bean(name="credentialsMatcher")
    public CredentialsMatcher credentialsMatcher() {
        return new CredentialsMatcher();
    }
    @Bean
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){
        return new LifecycleBeanPostProcessor();
    }
    @Bean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){
        DefaultAdvisorAutoProxyCreator creator=new DefaultAdvisorAutoProxyCreator();
        creator.setProxyTargetClass(true);
        return creator;
    }
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(@Qualifier("securityManager") SecurityManager manager) {
        AuthorizationAttributeSourceAdvisor advisor=new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(manager);
        return advisor;
    }
}
— - - -- - -- - -- - -- - - -- - - - -- 
public class AuthRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    //認(rèn)證.登錄
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken utoken=(UsernamePasswordToken) token;//獲取用戶(hù)輸入的token
        String username = utoken.getUsername();
        User user = userService.selectByPhone(username);
        return new SimpleAuthenticationInfo(user, user.getPassword(),this.getClass().getName());//放入shiro.調(diào)用CredentialsMatcher檢驗(yàn)密碼
    }
    //授權(quán)
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        User user=(User) principal.fromRealm(this.getClass().getName()).iterator().next();//獲取session中的用戶(hù)
        List<String> permissions=new ArrayList<>();
        Set<Role> roles = user.getRoleList();
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        List<String> listrole = new ArrayList<>();
        if(roles.size()>0) {
            for(Role role : roles) {
                if(!listrole.contains(role.getRole())){
                    listrole.add(role.getRole());
                }
                Set<Module> modules = role.getModules();
                if(modules.size()>0) {
                    for(Module module : modules) {
                        permissions.add(module.getMname());
                    }
                }
            }
        }
        info.addRoles(listrole);                       //將角色放入shiro中.
    info.addStringPermissions(permissions);         //將權(quán)限放入shiro中.
        return info;
    }
}
//自定義密碼比較器
public class CredentialsMatcher extends SimpleCredentialsMatcher {
    private  Logger logger = Logger.getLogger(CredentialsMatcher.class);
    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        UsernamePasswordToken utoken=(UsernamePasswordToken) token;
        //所需加密的參數(shù)  即  用戶(hù)輸入的密碼
        String source = String.valueOf(utoken.getPassword());
        //[鹽] 一般為用戶(hù)名 或 隨機(jī)數(shù)
        String salt = utoken.getUsername();
        //加密次數(shù)
        int hashIterations = 50;
        SimpleHash sh = new SimpleHash("md5", source, salt, hashIterations);
        String Strsh =sh.toHex();
        //打印最終結(jié)果
        logger.info("正確密碼為:"+Strsh);
        //獲得數(shù)據(jù)庫(kù)中的密碼
        String dbPassword= (String) getCredentials(info);
        logger.info("數(shù)據(jù)庫(kù)密碼為:"+dbPassword);
        //進(jìn)行密碼的比對(duì)
        return this.equals(Strsh, dbPassword);
    }
}

4、登錄控制器

    @RequestMapping("/loginUser")
    public String loginUser(String username,String password,HttpSession session) {
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();
        Map map=new HashMap();
        try {
            subject.login(usernamePasswordToken);   //完成登錄
            User user=(User) subject.getPrincipal();
            session.setAttribute("user", user);
            return "index";
        } catch (IncorrectCredentialsException e) {
            map.put("msg", "密碼錯(cuò)誤");
        } catch (LockedAccountException e) {
            map.put("msg", "登錄失敗,該用戶(hù)已被凍結(jié)");
        } catch (AuthenticationException e) {
            map.put("msg", "該用戶(hù)不存在");
        } catch (Exception e) {
            return "login";//返回登錄頁(yè)面
        }
        return map.toString();
    }

5、thymeleaf頁(yè)面權(quán)限控制

<html lang="zh_CN" xmlns:th="http://www.thymeleaf.org"
	  xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
	  
//作為屬性控制
<button  type="button" shiro:authenticated="true" class="btn btn-outline btn-default">
	<i class="glyphicon glyphicon-plus" aria-hidden="true"></i>
</button>
//作為標(biāo)簽
<shiro:hasRole name="admin">
	<button type="button" class="btn btn-outline btn-default">
		<i class="glyphicon glyphicon-heart" aria-hidden="true"></i>
	</button>
</shiro:hasRole>

6、標(biāo)簽說(shuō)明

guest標(biāo)簽
  <shiro:guest>
  </shiro:guest>
  用戶(hù)沒(méi)有身份驗(yàn)證時(shí)顯示相應(yīng)信息,即游客訪(fǎng)問(wèn)信息。
user標(biāo)簽
  <shiro:user>  
  </shiro:user>
  用戶(hù)已經(jīng)身份驗(yàn)證/記住我登錄后顯示相應(yīng)的信息。
authenticated標(biāo)簽
  <shiro:authenticated>  
  </shiro:authenticated>
  用戶(hù)已經(jīng)身份驗(yàn)證通過(guò),即Subject.login登錄成功,不是記住我登錄的。
notAuthenticated標(biāo)簽
  <shiro:notAuthenticated>
  
  </shiro:notAuthenticated>
  用戶(hù)已經(jīng)身份驗(yàn)證通過(guò),即沒(méi)有調(diào)用Subject.login進(jìn)行登錄,包括記住我自動(dòng)登錄的也屬于未進(jìn)行身份驗(yàn)證。
principal標(biāo)簽
  <shiro: principal/>
  
  <shiro:principal property="username"/>
  相當(dāng)于((User)Subject.getPrincipals()).getUsername()。
lacksPermission標(biāo)簽
  <shiro:lacksPermission name="org:create">
 
  </shiro:lacksPermission>
  如果當(dāng)前Subject沒(méi)有權(quán)限將顯示body體內(nèi)容。
hasRole標(biāo)簽
  <shiro:hasRole name="admin">  
  </shiro:hasRole>
  如果當(dāng)前Subject有角色將顯示body體內(nèi)容。
hasAnyRoles標(biāo)簽
  <shiro:hasAnyRoles name="admin,user">
   
  </shiro:hasAnyRoles>
  如果當(dāng)前Subject有任意一個(gè)角色(或的關(guān)系)將顯示body體內(nèi)容。
lacksRole標(biāo)簽
  <shiro:lacksRole name="abc">  
  </shiro:lacksRole>
  如果當(dāng)前Subject沒(méi)有角色將顯示body體內(nèi)容。
hasPermission標(biāo)簽
  <shiro:hasPermission name="user:create">  
  </shiro:hasPermission>
  如果當(dāng)前Subject有權(quán)限將顯示body體內(nèi)容

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java自動(dòng)添加重寫(xiě)的toString方法詳解

    Java自動(dòng)添加重寫(xiě)的toString方法詳解

    在本篇文章里小編給大家整理了關(guān)于Java自動(dòng)添加重寫(xiě)的toString方法總結(jié),需要的朋友們學(xué)習(xí)下。
    2019-07-07
  • Java中JVM常用參數(shù)配置教程(提供配置示例)

    Java中JVM常用參數(shù)配置教程(提供配置示例)

    這篇文章主要給大家介紹了關(guān)于Java中JVM常用參數(shù)配置的相關(guān)資料, jvm的參數(shù)有很多,必須知道參數(shù)分類(lèi)并且記住面試常見(jiàn)的幾個(gè)參數(shù),文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-06-06
  • java小程序之控制臺(tái)字符動(dòng)畫(huà)的實(shí)現(xiàn)

    java小程序之控制臺(tái)字符動(dòng)畫(huà)的實(shí)現(xiàn)

    這篇文章主要給大家介紹了java小程序之控制臺(tái)字符動(dòng)畫(huà)實(shí)現(xiàn)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-04-04
  • Java方法參數(shù)傳遞如何實(shí)現(xiàn)

    Java方法參數(shù)傳遞如何實(shí)現(xiàn)

    這篇文章主要介紹了Java方法參數(shù)傳遞如何實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-05-05
  • 導(dǎo)入SpringCloud依賴(lài)踩的坑及解決

    導(dǎo)入SpringCloud依賴(lài)踩的坑及解決

    這篇文章主要介紹了導(dǎo)入SpringCloud依賴(lài)踩的坑及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-04-04
  • SpringBoot攔截器的使用小結(jié)

    SpringBoot攔截器的使用小結(jié)

    今天給大家總結(jié)一下SpringBoot下攔截器的使用,需要的朋友參考下吧
    2017-05-05
  • Java處理日期時(shí)間的方法匯總

    Java處理日期時(shí)間的方法匯總

    這篇文章主要給大家介紹了利用Java中的Calendar 類(lèi)處理日期時(shí)間的方法匯總,其中包括取日期的每部分、取當(dāng)月的第一天或最后一天、求兩個(gè)日期之間相隔的天數(shù)以及一年前的日期等等的示例代碼,有需要的朋友們可以直接參考借鑒,下面來(lái)一起看看吧。
    2016-12-12
  • SpringBoot項(xiàng)目接入MQTT的詳細(xì)指南

    SpringBoot項(xiàng)目接入MQTT的詳細(xì)指南

    MQTT是一種輕量級(jí)的消息傳輸協(xié)議,特別適用于物聯(lián)網(wǎng)(IoT)場(chǎng)景,具有低帶寬、高延遲網(wǎng)絡(luò)環(huán)境下的優(yōu)勢(shì),SpringBoot作為流行的 Java開(kāi)發(fā)框架,能夠方便地與MQTT集成,實(shí)現(xiàn)高效的消息通信,本文將詳細(xì)介紹如何在SpringBoot項(xiàng)目中接入MQTT,需要的朋友可以參考下
    2025-03-03
  • mybatis自動(dòng)建表的實(shí)現(xiàn)方法

    mybatis自動(dòng)建表的實(shí)現(xiàn)方法

    這篇文章主要介紹了mybatis自動(dòng)建表的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • JPA如何將查詢(xún)結(jié)果轉(zhuǎn)換為DTO對(duì)象

    JPA如何將查詢(xún)結(jié)果轉(zhuǎn)換為DTO對(duì)象

    這篇文章主要介紹了JPA如何將查詢(xún)結(jié)果轉(zhuǎn)換為DTO對(duì)象,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-02-02

最新評(píng)論

田阳县| 永顺县| 诸城市| 宜兴市| 色达县| 舞钢市| 阳谷县| 唐海县| 文成县| 哈密市| 始兴县| 图们市| 于田县| 卢湾区| 治县。| 吴忠市| 唐山市| 灌云县| 宁国市| 全椒县| 深州市| 阿合奇县| 郑州市| 德江县| 丽江市| 镇原县| 静宁县| 德阳市| 拉孜县| 沁阳市| 涟水县| 美姑县| 鄂伦春自治旗| 巴东县| 惠安县| 峨眉山市| 双流县| 浙江省| 宽城| 宣威市| 建湖县|