在jsp页面中我们可以使用spring security提供的权限标签来进行权限控制
1.maven依赖导入
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>${spring.security.version}</version>
</dependency>
<!-- 没有上面的那个会可能出错 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${spring.security.version}</version>
</dependency>
2.jsp页面导入
<%@taglib uri="http://www.springframework.org/security/tags" prefix="security"%>
3.常用标签
在jsp中我们可以使用以下三种标签,其中authentication代表的是当前认证对象,可以获取当前认证对象信息,例如用户名。其它两个标签我们可以用于权限控制
3.1 authentication
获取正在操作的用户信息
authentication
<security:authentication property="" htmlEscape="" scope="" var=""/>
property:只允许指定Authentication所拥有的属性,可以进行属性的级联获取,如“principle.username”,不允许直接通过方法进行调用
htmlEscape:表示是否需要将html进行转义。默认为true。
scope:与var属性一起使用,用于指定存放获取的结果的属性名的作用范围,默认我pageContext。Jsp中拥有的作用范围都进行进行指定
var:用于指定一个属性名,这样当获取到了authentication的相关信息后会将其以var指定的属性名进行存放,默认是存放在pageConext中
demo:
放在登录后显示用户名
jsp
<security:authentication property="principal.username"/>
3.2 authorize
用于控制页面标签是否展示
authorize
是用来判断普通权限的,通过判断用户是否具有对应的权限而控制其所包含内容的显示
<security:authorize access="" method="" url="" var=""></security:authorize>
access:需要使用表达式来判断权限,当表达式的返回结果为true时表示拥有对应的权限method:method属性是配合url属性一起使用的,表示用户应当具有指定url指定method访问的权限,method的默认值为GET,可选值为http请求的7种方法url:
url表示如果用户拥有访问指定url的权限即表示可以显示authorize标签包含的内容
var:用于指定将权限鉴定的结果存放在pageContext的哪个属性中
demo:
jsp
<li id="system-setting">
<security:authorize access="hasRole('ADMIN')">
<a href="${pageContext.request.contextPath}/user/findAll.do"> <i
class="fa fa-circle-o"></i> 用户管理</a>
</security:authorize>
</li>
如果报jsp页面异常
即
JspException: No visible WebSecurityExpressionHandler instance could be found in the application context. There must be at least one in order to support expressions in JSP ‘authorize’ tags.
spring-security.xml加入
<bean id="webexpressionHandler" class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler" />
或者
spring-security.xml修改
<security:http auto-config="true" use-expressions="false">
<!-- 配置具体的拦截的规则 pattern="请求路径的规则"
access="访问系统的人,必须有ROLE_USER或ROLE_ADMIN的角色" -->
<security:intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN"/>
...
改为
<security:http auto-config="true" use-expressions="true">
<!-- 配置具体的拦截的规则 pattern="请求路径的规则"
access="访问系统的人,必须有ROLE_USER或ROLE_ADMIN的角色" -->
<security:intercept-url pattern="/**" access="hasAnyRole('ROLE_ADMIN','ROLE_USER')"/>
...
3.3 accesscontrollist
accesscontrollist
标签是用于鉴定ACL权限的。其一共定义了三个属性:hasPermission、domainObject和var,其中前两个是必须指定的
<security:accesscontrollist hasPermission="" domainObject="" var=""></security:accesscontrollist>
hasPermission:hasPermission属性用于指定以逗号分隔的权限列表domainObject:domainObject用于指定对应的域对象var:var则是用以将鉴定的结果以指定的属性名存入pageContext中,以供同一页面的其它地方使用