shiro權限框架,前端驗證是爲jsp設計的,其中的tag只能用於jsp系列的模板引擎。最近項目使用了thymeleaf作爲前端模板引擎,使用HTML文件,沒法引入shiro的tag lib,此時如果要使用shiro的話,可以引入 thymeleaf-extras-shiro.jar這個拓展包來曲線實現shiro的前端驗證。
在pom.xml中加入如下依賴:
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>1.0.2</version>
</dependency>
關於版本,可以在maven倉庫中查詢:http://mvnrepository.com/artifact/com.github.theborakompanioni/thymeleaf-extras-shiro/1.0.2
thymeleaf-extras-shiro.jar在git hub的地址:https://github.com/theborakompanioni/thymeleaf-extras-shiro,上面有具體的使用說明。
引入jar包後,我們要簡單設置一下thymeleaf的引擎:
<bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
<property name="additionalDialects">
<set>
<bean class="at.pollux.thymeleaf.shiro.dialect.ShiroDialect"/>
</set>
</property>
</bean>
或者如果使用的是Java代碼配置的話:
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
Set<IDialect> additionalDialects = new HashSet<IDialect>();
additionalDialects.add(new ShiroDialect());
templateEngine.setAdditionalDialects(additionalDialects);
return templateEngine;
}
然後就可以在頁面中使用thymeleaf化的shiro標籤來進行前端驗證了。
shiro本身的標籤有限,沒有hasAnyPermission標籤,我在之前的一篇文章中《自定義shiro標籤》有寫過jsp標籤的版本,其實,在這裏如果使用的是thymeleaf,也可以自定義拓展一下shiro的hasAnyPermission。
將下載下來的thymeleaf-extras-shiro.jar打開,會有一個shiro-dialect.xml的文件,這裏定義了thymeleaf的shiro屬性,我們也可以根據這裏面的例子進行簡單拓展。
這裏其實是在拓展thymeleaf,官方文檔中有詳細的說明和簡單例子,對照文檔,學習會更快。