栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java自定义简单标签实例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java自定义简单标签实例

下面将以权限的控制为例自定义一个标签:
一、标签类型
复制代码 代码如下:


步骤:
1.自定义一个类PerssionTag 继承SimpleTagSupport(自定义标签一般都会继承这个类)
复制代码 代码如下:
package cn.com.liveuc.privilege.tag;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import cn.com.liveuc.privilege.model.Privilege;
import cn.com.liveuc.privilege.model.Resource;
import cn.com.liveuc.privilege.model.Role;
import cn.com.liveuc.privilege.model.User;

public class PerssionTag extends SimpleTagSupport {

 //自定义标签属性,用于标签传入参数
 private String uri;

 //接收标签传入的参数
 public void setUri(String uri) {
  this.uri = uri;
 }
 @Override
 public void doTag() throws JspException, IOException {
  //获取用户登陆后保存的Session
  PageContext page = (PageContext) this.getJspContext();
  User user = (User) page.getSession().getAttribute("login");
  //如果用户登陆
  if(user != null) {
   //用户登陆判断用户权限
   List list = new ArrayList();
   //获取用户的角色
   Set role = user.getRole();
   for(Role r:role) {
    //获取角色对应的权限
    Set privilege = r.getPrivilege();
    for(Privilege p:privilege) {
     //获取权限对应的资源
     Set res = p.getResource();
     for(Resource re:res) {
      list.add(re.getUri());
     }
    }
   }
   for(String ur:list) {
    //判断用户的权限
    if(ur.equals(uri)) {
     this.getJspBody().invoke(null); //有权限输出标签体内容
    }
   }
  }
 }
}

2.在WEB-INF下创建tld文件描述标签。
复制代码 代码如下:

 version="2.0"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">
                     the Apache Struts framework includes a library of custom tags.
                    The tags interact with the framework's validation and internationalization features;
                    to ensure that input is correct and output is localized.
                    The Struts Tags can be used with JSP FreeMarker or Velocity."]]>

 "Struts Tags"
 2.2.3
 s
 /wxt
 
  per
  cn.com.liveuc.privilege.tag.PerssionTag
  scriptless
  
  
   uri
   true
   true
  
 



3.运用标签
在Jsp页面导入标签:
%@taglib prefix="wxt" uri="/wxt" %
运用标签:

      用户管理

用户权限包含uri资源的将会输出标签内容。 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/153064.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号