thymeleaf模板引擎和shiro架構的整合,thymeleafshiro
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
引入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,官方文檔中有詳細的說明和簡單例子,對照文檔,學習會更快。