做thymeleaf和spring security整合的时候
页面的thymeleaf关于spring security的命名空间并没有产生效果
开始以为是版本问题,反复调整都没有作用,最后在thymeleaf-extras-springsecuritygit源码下的说明中才发现自己没有在
SpringTemplateEngine中显式的引入方言类,即:
<bean id="templateEngine" class="org.thymeleaf.spring5.SpringTemplateEngine">
...
<property name="additionalDialects">
<set>
<!-- Note the package would change to 'springsecurity[3|4]' if you are using that version -->
<bean class="org.thymeleaf.extras.springsecurity5.dialect.SpringSecurityDialect"/>
</set>
</property>
...
</bean>
为了以后不会在犯相同错误我整理一下spring security 与thymeleaf整合的流程:
除开thymeleaf基础的依赖包:org.thymeleaf-x.x.x.release.jar,org.thymeleaf-spring*-x.x.x.release.jar(这个jar包用来和spring整合)
这里直接贴我的maven:
<dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring4</artifactId> <version>3.0.9.RELEASE</version> </dependency> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf</artifactId> <version>3.0.9.RELEASE</version> </dependency>
以及spring security的依赖包:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
额外引入依赖包spring security和thymeleaf整合用的依赖包:
thymeleaf-extras-springsecurity*.jar
<dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity4</artifactId> <version>3.0.4.RELEASE</version> </dependency>
(可以到git上查看相互版本配对关系,以避免版本不兼容)
https://github.com/thymeleaf/thymeleaf-extras-springsecurity
然后就是配置文件:
<!-- 使用thymeleaf解析 -->
<bean id="templateResolver"
class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
<property name="prefix" value="/WEB-INF/page/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML" />
<property name="cacheable" value="false" />
<property name="characterEncoding" value="UTF-8"/>
</bean>
<bean id="templateEngine"
class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
<property name="additionalDialects">
<set>
<bean class="org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect"/>
</set>
</property>
</bean>
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
<property name="characterEncoding" value="UTF-8"/>
</bean>
记住 根据引入的thymeleaf版本如(thymeleaf-spring4,thymeleaf-spring5...)不同,bean的类路径也会发生变化
最后就是在页面头加命名空间了,如下:
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
学习框架建议先把git官网下的框架介绍开一遍,否则就会像我一样在网上查了n久,结果在git官网上才发现问题所在。
然后这是第一次写博客,如果没讲清楚,让你误解了,万望海涵。嗯,相互学习,相互促进吧。