Freemarker的Shiro标签:
在SpringBoot里面并不是直接支持JSP文件的,然后我就在项目中使用了Freemarker,但是Shiro标签并不能直接支持.ftl文件,所以我们需要先引入一个Maven依赖.
<!--freemarker的Shiro标签-->
<dependency>
<groupId>net.mingsoft</groupId>
<artifactId>shiro-freemarker-tags</artifactId>
<version>1.0.2</version>
</dependency>
然后,我们写一个名为ShiroTagsFreeMarkerCfg配置类来对Freemark使用Shiro标签进行配置.当然了,要确定配置类能被正确注入到Bean中,代码如下所示.
import com.jagregory.shiro.freemarker.ShiroTags;
import freemarker.template.TemplateModelException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import javax.annotation.PostConstruct;
@Component
public class ShiroTagsFreeMarkerCfg {
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
@PostConstruct
public void setSharedVariable() throws TemplateModelException {
freeMarkerConfigurer.getConfiguration().setSharedVariable("shiro", new ShiroTags());
}
}
配置类搞好之后,我们就可以在.ftl文件中使用Shiro的权限标签了,标签格式如下所示.
<@shiro.guest>
游客访问 <a href = "login.jsp"></a>
</@shiro.guest>
user 标签:用户已经通过认证\记住我 登录后显示响应的内容
<@shiro.user>
欢迎[<@shiro.principal/>]登录,<a href="/logout.html">退出</a>
</@shiro.user>
authenticated标签:用户身份验证通过,即 Subjec.login 登录成功 不是记住我登录的
<@shiro.authenticated>
用户[<@shiro.principal/>]已身份验证通过
</@shiro.authenticated>
notAuthenticated标签:用户未进行身份验证,即没有调用Subject.login进行登录,包括"记住我"也属于未进行身份验证
<@shiro.notAuthenticated>
当前身份未认证(包括记住我登录的)
</@shiro.notAuthenticated>
principal 标签:显示用户身份信息,默认调用
Subjec.getPrincipal()获取,即Primary Principal
<@shiro.principal property="username"/>
hasRole标签:如果当前Subject有角色将显示body体内的内容
<@shiro.hasRole name="admin">
用户[<@shiro.principal/>]拥有角色admin<br/>
</@shiro.hasRole>
hasAnyRoles标签:如果Subject有任意一个角色(或的关系)将显示body体里的内容
<@shiro.hasAnyRoles name="admin,user,member">
用户[<@shiro.principal/>]拥有角色admin或user或member<br/>
</@shiro.hasAnyRoles>
lacksRole:如果当前 Subjec没有角色将显示body体内的内容
<@shiro.lacksRole name="admin">
用户[<@shiro.principal/>]不拥有admin角色
</@shiro.lacksRole>
hashPermission:如果当前Subject有权限将显示body体内容
<@shiro.hasPermission name="user:add">
用户[<@shiro.principal/>]拥有user:add权限
</@shiro.hasPermission>
lacksPermission:如果当前Subject没有权限将显示body体内容
<@shiro.lacksPermission name="user:add">
用户[<@shiro.principal/>]不拥有user:add权限
</@shiro.lacksPermission>