1.引入依赖
我用的Maven源是阿里云,如果是其他源,请自己去查版本号,
<!-- shiro-freemarker-tags start -->
<dependency>
<groupId>net.mingsoft</groupId>
<artifactId>shiro-freemarker-tags</artifactId>
<version>1.0.2</version>
<exclusions>
<exclusion>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-all</artifactId>
</exclusion>
<exclusion>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- shiro-freemarker-tags end -->
2.Freemarker集成Shiro标签
import com.jagregory.shiro.freemarker.ShiroTags;
import freemarker.template.Configuration;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
/**
* 集成Shiro标签
*/
@Component
public class ShiroTagFreeMarkerConfigurer implements InitializingBean {
@Autowired
private Configuration configuration;
@Autowired
private FreeMarkerViewResolver resolver;
@Override
public void afterPropertiesSet() throws Exception {
// 加上这句后,可以在页面上使用shiro标签
configuration.setSharedVariable("shiro", new ShiroTags());
// 加上这句后,可以在页面上用${context.contextPath}获取contextPath
resolver.setRequestContextAttribute("context");
}
}
3. Shiro标签详解
1. guest(游客)
<@shiro.guest>
您当前是游客,<a href="javascript:void(0);">登录</a>
</@shiro.guest>
2. user(已经登录,或者记住我登录)
<@shiro.user>
欢迎[<@shiro.principal/>]登录,<a href="/logout.shtml">退出</a>
</@shiro.user>
3. authenticated(已经认证,排除记住我登录的)
<@shiro.authenticated>
用户[<@shiro.principal/>]已身份验证通过
</@shiro.authenticated>
4. notAuthenticated(和authenticated相反)
<@shiro.notAuthenticated>
当前身份未认证(包括记住我登录的)
</@shiro.notAuthenticated>
该功能主要用途:识别是不是本次操作登录过的,比如支付系统,进入系统可以用记住我的登录信息,但是当要关键操作的时候,需要进行认证识别。
5. principal标签
principal标签,取值取的是你登录的时候。在Realm实现类中的如下代码:
...
return new SimpleAuthenticationInfo(user,user.getPswd(), getName());
在 new SimpleAuthenticationInfo(第一个参数,....) 的第一个参数放的如果是一个username,那么就可以直接用。
<!--从shiro中获取-->
<@shiro. principal/>
<!--如果存的是对象,可以通过property取值-->
<@shiro.principal property="username"/>
如果第一个参数放的是对象,比如放User对象。那么如果要取username字段。
<!--需要指定property-->
<@shiro.principal property="username"/>
和Java如下Java代码一致
User user = (User) SecurityUtils.getSubject().getPrincipals();
String username = user.getUsername();
6. hasRole标签(判断是否拥有这个角色)
<@shiro.hasRole name="admin">
用户[<@shiro.principal/>]拥有角色admin<br/>
</@shiro.hasRole>
7. hasAnyRoles标签(判断是否拥有这些角色的其中一个)
<@shiro.hasAnyRoles name="admin,user,member">
用户[<@shiro.principal/>]拥有角色admin或user或member<br/>
</@shiro.hasAnyRoles>
8. lacksRole标签(判断是否不拥有这个角色)
<@shiro.lacksRole name="admin">
用户[<@shiro.principal/>]不拥有admin角色
</@shiro.lacksRole>
9. hasPermission标签(判断是否有拥有这个权限)
<@shiro.hasPermission name="user/add">
用户[<@shiro.principal/>]拥有user/add权限
</@shiro.hasPermission>
10. lacksPermission标签(判断是否没有这个权限)
<@shiro.lacksPermission name="user/add">
用户[<@shiro.principal/>]不拥有user/add权限
</@shiro.lacksPermission>