1. 以下为java代码:
package com.fh.tag;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.fh.service.system.permission.PermissionService;
public class PermissionTag extends BodyTagSupport {
/**
*
*/
private static final long serialVersionUID = -8534443755590632585L;
private String res;
public String getRes() {
return res;
}
public void setRes(String res) {
this.res = res;
}
@Override
public int doStartTag() throws JspException {
HttpServletRequest request = (HttpServletRequest)this.pageContext.getRequest();
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
PermissionService permissionService = (PermissionService)wac.getBean("permissionService");
try {
if (permissionService.hasPermissionRes(res)) {
return EVAL_BODY_INCLUDE;
} else {
return SKIP_BODY;
}
} catch (Exception e1) {
e1.printStackTrace();
return SKIP_BODY;
}
}
}
-
以下为java代码的项目位置:
-
以下为tld文件的代码:
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd"> <taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>permTag</short-name> <uri>http://itheima/permTag</uri> <display-name>Common Tag</display-name> <description>Common Tag library</description> <tag> <name>perm</name> <tag-class>com.fh.tag.PermissionTag</tag-class> <body-content>JSP</body-content> <attribute> <name>res</name> <required>false</required> <rtexprvalue>true</rtexprvalue> <type>java.lang.String</type> </attribute> </tag> </taglib>
-
以下为tld文件的项目位置:
-
在jsp页面中应用tag:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <%@ taglib prefix="permTag" uri="http://itheima/permTag"%> <!DOCTYPE html> <html lang="en"> <head> <base href="<%=basePath%>"> <!-- jsp文件头和头部 --> <%@ include file="../admin/top.jsp"%> <link type="text/css" href="http://code.jquery.com/ui/1.9.1/themes/smoothness/jquery-ui.css" rel="stylesheet" /> <link rel="stylesheet" href="static/css/jquery-ui-timepicker-addon.css"/> <link rel="stylesheet" href="static/css/jquery-ui-timepicker-addon.css"/> </head> <body> <permTag:perm res="user/addUser.button"> <a>按钮</a> </permTag:perm> </body>