片段出自 **Velocity 模板文件 (.vm)**,而非 Java 源碼:
#Authorize("updateState.do")
<a href="javascript:updateStates();" class="But02">修改</a>
#end
// Velocity 配置
velocityEngine.setProperty("userdirective", "authorize,com.example.velocity.AuthorizeDirective");
// 自定義指令
public class AuthorizeDirective implements Directive {
@Override
public void render(InternalContextAdapter context, Writer writer, Node node)
throws IOException, TemplateException {
String resource = (String) node.jjtGetChild(0).value(context); // "updateState.do"
Subject subject = SecurityUtils.getSubject();
if (subject.isPermitted(resource)) {
node.render(context, writer); // 輸出包裹內容
}
// 無權限則不輸出任何內容
}
}
| 模板引擎 | 權限控制標籤 |
|---|---|
| JSP (Shiro Taglib) | ` |
| Thymeleaf (Spring Security) | `修改` |
| Velocity (自定義) | `#Authorize("updateState.do") ... #end` |
認清「Velocity 模板指令 ≠ Java 語法」,權限標籤原理一目瞭然。