上篇提到了,将用户,角色,组,权限存放到数据库中,会遇到UI上spring security 标签失效问题,建议自己定义自定义标签,下面就自定义标签,具体说一下思路;
spring security 登陆时将用户信息存放于session中,在自定义标签中通过pageContext 获取session相关信息,通过相应传人的URL,进行相应的比对就可以判断某些URL是否有访问权限,进而控制是否显示。
下面是一个简单的自定义标签的例子,如果URL为空,则不显示超链接,否则就显示,在现实中这个判断可以和spring security 结合使用:
tag的java类
/**
*
*/
package org.springsecurity.tag;
import javax.servlet.jsp.tagext.BodyTagSupport;
/**
* @author jgao1
*
*/
public class AuthorizeTag extends BodyTagSupport {
private static final long serialVersionUID = 1L;
private String URL;
public String getURL() {
return URL;
}
public void setURL(String uRL) {
URL = uRL;
}
@Override
public int doStartTag() {
// 如果URL不空就显示URL,否则就不显
if (null != URL && !"".equals(URL)) {
return EVAL_BODY_INCLUDE;
}
return this.SKIP_BODY;
}
}
authorize.tld
<?xml version="1.0" encoding="UTF-8" ?> <taglib xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd" version="2.1"> <description> <![CDATA[security Tags]]> </description> <tlib-version>1.0</tlib-version> <short-name>security</short-name> <uri>http://www.springsecurity.org/jsp</uri> <tag> <description> <![CDATA[authorize Tag]]> </description> <name>authorize</name> <tag-class> org.springsecurity.tag.AuthorizeTag </tag-class> <body-content>JSP</body-content> <attribute> <name>URL</name> <required>false</required> <rtexprvalue>true</rtexprvalue> <type>java.lang.String</type> </attribute> </tag> </taglib>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<taglib>
<taglib-uri>http://www.springsecurity.org/jsp</taglib-uri>
<taglib-location>/WEB-INF/authorize.tld</taglib-location>
</taglib>
</web-app>
index,jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springsecurity.org/jsp" prefix="security"%>
<body>
<security:authorize URL="qqq">
<a href="admin.jsp">进入admin页面</a>
</security:authorize>
<security:authorize URL="">
<a href="admin.jsp">进入admin页面</a>
</security:authorize>
</body>
通过测试会发现,
第一个标签显示,第二个标签不显示,目的已达到,另外,自定义标签教程,方便以后查询