分享一个java拼接html的工具类

package com.zhou.util;

import java.util.*;
import java.util.regex.Pattern;

/**
 * 生成html
 * @author lang.zhou
 * @date   2019-02-01
 * @version v2.0 append(Tag)支持动态修改Tag属性
 */
public class Tag2 implements Cloneable{
    public static final String SINGLE_DOLT="'";
    public static final String DOUBLE_DOLT="\"";
    public static final String SPACE=" ";
    public static final String BR="<br>";
    /*** 定义HTML标签的正则表达式*/
    public static final String REGEX_HTML = "<[^>]+>";
    public static Pattern htmlPattern = null;
    /*** false代表有标签体*/
    private boolean single=false;
    /*** style标签使用的引号*/
    private String styleDolt;
    /*** 标签名称*/
    private String name;
    /*** 标签属性*/
    private Map<String,Two> attributes;
    /*** 标签css*/
    private Map<String,String> css;
    /*** 标签之前的元素*/
    private List<Object> beforeElements;
    /*** 标签体内的元素*/
    private List<Object> body;
    /*** 标签后面的元素*/
    private List<Object> afterElements;

    public Tag2(String name){
        this.name=name;
    }
    public Tag2(String name, boolean single){
        this.name=name;
        this.single=single;
    }
    public void setName(String name){
        this.name=name;
    }
    /**
     * 添加一个属性,添加style属性时,和css()不冲突
     * @param name 属性名
     * @param value 属性值,默认使用双引号
     */
    public Tag2 attr(String name, String value){
        return attr(name,value,DOUBLE_DOLT);
    }
    /**
     * 获得一个属性的值
     * @param name 属性名
     */
    public String attr(String name){
        if(this.attributes != null){
            Two two=this.attributes.get(name);
            return two != null ? two.value : null;
        }
        return null;
    }

    /**
     * @param dolt 有效的值为单引号或双引号,表示这个属性值用哪个引号包裹,如href=""或href=''
     */
    public Tag2 attr(String name, String value, String dolt){
        if(attributes==null){
            attributes=new HashMap<>();
        }
        Two t=new Two(value,dolt);
        attributes.put(name,t);
        return this;
    }
    /**
     * 添加一个css属性,和attr("style","xxx")不冲突
     * @param name 属性名
     * @param value 属性值
     */
    public Tag2 css(String name, String value){
        if(css==null){
            css=new HashMap<>();
        }
        css.put(name,value);
        return this;
    }
    public Tag2 clazz(String className){
        return attr("class",className);
    }
    private Tag2 addBody(Object o, int index){
        if(!single){
            if(body==null){
                body=new ArrayList<>();
            }
            if(index==-1){
                body.add(o);
            }else{
                body.add(index,o);
            }
        }
        return this;
    }
    /**
     * 在标签体内(末尾)追加一个元素,和jquery的append一样
     * @param o Tag对象或者字符串
     */
    public Tag2 append(Object o){
        return addBody(o,-1);
    }
    public Tag2 appendBr(){
        return addBody(Tag2.BR,-1);
    }
    /**
     * 在标签体内(开头)追加一个元素,和jquery的prepend一样
     * @param o Tag对象或者字符串
     */
    public Tag2 prepend(Object o){
        return addBody(o,0);
    }
    /**
     * 在标签后面追加一个元素,和jquery的after一样
     * @param o Tag对象或者字符串
     */
    public Tag2 after(Object o){
        if(afterElements==null){
            afterElements=new ArrayList<>();
        }
        afterElements.add(o);
        return this;
    }
    /**
     * 在标签前面追加一个元素,和jquery的before一样
     * @param o Tag对象或者字符串
     */
    public Tag2 before(Object o){
        if(beforeElements==null){
            beforeElements=new ArrayList<>();
        }
        beforeElements.add(o);
        return this;
    }
    public boolean is(String name){
        return this.name != null && Objects.equals(this.name,name);
    }
    /**
     * 将标签转换为字符串
     * @return 标签的字符串
     */
    public String html(){
        if(name == null || "".equals(name)){
            return null;
        }
        StringBuilder s=new StringBuilder();
        if(beforeElements!=null && beforeElements.size()>0){
            for(Object e : beforeElements){
                s.append(e);
            }
        }
        s.append("<").append(name);
        String[] styles;
        if(attributes!=null && !attributes.isEmpty()){
            Two t=attributes.get("style");
            if(t!=null){
                styles=t.value.split(";");
                styleDolt=t.dolt;
                if(styles.length>0){
                    if(css==null){
                        css=new HashMap<>();
                    }
                    for (String style : styles) {
                        if (style.contains(":") && style.split(":").length > 1) {
                            css.put(style.split(":")[0], style.split(":")[1]);
                        }
                    }
                }
            }
            for (Map.Entry<String, Two> entry : attributes.entrySet()) {
                if (!"style".equals(entry.getKey())) {
                    String value = entry.getValue().value;
                    if (value != null && !"".equals(value)) {
                        s.append(" ").append(entry.getKey()).append("=").append(entry.getValue().dolt)
                                .append(value).append(entry.getValue().dolt);
                    }
                }
            }
        }
        if(css!=null && !css.isEmpty()){
            boolean haveStyle=false;
            for(String v : css.values()){
                if(v!=null && !"".equals(v)){
                    haveStyle=true;
                    break;
                }
            }
            if(haveStyle){
                if(styleDolt==null){
                    styleDolt=DOUBLE_DOLT;
                }
                s.append(" style=").append(styleDolt);
                for(Map.Entry<String,String> entry : css.entrySet()){
                    if(entry.getValue()!=null && !"".equals(entry.getValue())){
                        s.append(entry.getKey()).append(":").append(entry.getValue()).append(";");
                    }
                }
                s.append(styleDolt);
            }
        }
        if(!single){
            s.append(">");
            if(body!=null && body.size()>0){
                for(Object e : body){
                    s.append(e);
                }
            }
            s.append("</").append(name).append(">");
        }else{
            s.append("/>");
        }
        if(afterElements!=null && afterElements.size()>0){
            for(Object e : afterElements){
                s.append(e);
            }
        }
        return s.toString();
    }
    public Tag2 width(String wid){
        return css("width",wid);
    }
    public Tag2 height(String hi){
        return css("height",hi);
    }
    public Tag2 onClick(String func){
        return onClick(func,DOUBLE_DOLT);
    }
    public Tag2 onClick(String func, String dolt){
        return attr("onclick",func,dolt);
    }

    public Tag2 onChange(String func){
        return onChange(func,DOUBLE_DOLT);
    }
    public Tag2 onChange(String func, String dolt){
        return attr("onchange",func,dolt);
    }

    public Tag2 onInput(String func){
        return onInput(func,DOUBLE_DOLT);
    }
    public Tag2 onInput(String func, String dolt){
        return attr("oninput",func,dolt);
    }

    public Tag2 val(String value){
        return val(value,DOUBLE_DOLT);
    }
    public Tag2 val(String value, String dolt){
        return attr("value",value,dolt);
    }

    public Tag2 href(String href){
        return href(href,DOUBLE_DOLT);
    }
    public Tag2 href(String href, String dolt){
        if(this.is("a")){
            return attr("href",href,dolt);
        }
        return this;
    }
    public Tag2 cancleHref(){
        if(this.is("a")){
            return href("javascript:void(0);");
        }
        return this;
    }

    public Tag2 src(String src){
        return src(src,DOUBLE_DOLT);
    }
    public Tag2 src(String src, String dolt){
        return attr("src",src,dolt);
    }

    public Tag2 title(String title){
        return title(title,DOUBLE_DOLT);
    }
    public Tag2 title(String title, String dolt){
        return attr("title",title,dolt);
    }

    public Tag2 style(String style){
        return style(style,DOUBLE_DOLT);
    }
    public Tag2 style(String style, String dolt){
        return attr("style",style,dolt);
    }

    public Tag2 id(String id){
        return attr("id",id);
    }
    public Tag2 name(String name){
        return attr("name",name);
    }

    public Tag2 text(String text){
        if(body!=null){
            body.clear();
        }
        return append(text);
    }
    public String text(){
        if(body!=null){
            return this.html().replaceAll(REGEX_HTML,"");
        }
        return null;
    }
    public void empty(){
        if(this.body!= null){
            this.body.clear();
        }
        if(this.attributes!= null){
            this.attributes.clear();
        }
        if(this.css!= null){
            this.css.clear();
        }
        if(this.beforeElements!= null){
            this.beforeElements.clear();
        }
        if(this.afterElements!= null){
            this.afterElements.clear();
        }
    }

    public List<Object> children(){
        List<Object> tagList = new ArrayList<>();
        for(Object key : this.body){
            if(key != null){
                tagList.add(key);
            }
        }
        return tagList;
    }
    public static String getSpace(int n){
        StringBuilder s=new StringBuilder();
        for(int i=0;i<n;i++){
            s.append(SPACE);
        }
        return s.toString();
    }
    public static void main(String[] args){
        Tag2 div=new Tag2("div").style("background:#ffffff");
        Tag2 t = new Tag2("a").cancleHref().append("click me!");
        div.append(t).append("asd").title("measd");
        t.title("after insert title");
        //Tag2 a= Tag2.fromHtml(div.toString());

        System.out.println();

    }
    @Override
    public String toString(){
        return this.html();
    }
    private class Two{
        private String value;
        private String dolt;
        private Two(String value,String dolt){
            this.value=value;
            this.dolt=dolt;
        }
    }
    public static String toText(String str){
        if(htmlPattern == null){
            htmlPattern = Pattern.compile(REGEX_HTML);
        }
        return str == null || str.length() ==0 ? "" : htmlPattern.matcher(str).replaceAll("");
    }
    public Tag2 clone(){
        try {
            return (Tag2) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
            throw new RuntimeException("克隆对象失败!");
        }
    }
}

本人自己写的一个工具类,用于提高代码的简洁性:

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
以下是一个基本的TLV拼接工具类,用Java实现: ```java import java.util.ArrayList; import java.util.List; public class TLVUtils { /** * TLV编码 * @param tag 标签 * @param value 值 * @return TLV编码后的字节数组 */ public static byte[] encode(int tag, byte[] value) { int len = value.length; if (len > 127) { // 如果长度超过127,需要使用多字节表示长度 int byteNum = 1; int tempLen = len; while (tempLen > 0) { tempLen >>= 8; byteNum++; } byte[] lenBytes = new byte[byteNum]; lenBytes[0] = (byte) (0x80 | byteNum - 1); for (int i = 1; i < byteNum; i++) { lenBytes[byteNum - i] = (byte) (len & 0xFF); len >>= 8; } byte[] tlv = new byte[1 + byteNum + len]; tlv[0] = (byte) tag; System.arraycopy(lenBytes, 0, tlv, 1, byteNum); System.arraycopy(value, 0, tlv, 1 + byteNum, len); return tlv; } else { // 如果长度在0-127之间,直接使用1字节表示长度 byte[] tlv = new byte[1 + 1 + len]; tlv[0] = (byte) tag; tlv[1] = (byte) len; System.arraycopy(value, 0, tlv, 1 + 1, len); return tlv; } } /** * TLV解码 * @param data TLV编码后的字节数组 * @return List<TLV>对象 */ public static List<TLV> decode(byte[] data) { List<TLV> tlvList = new ArrayList<>(); int pos = 0; while (pos < data.length) { int tag = data[pos] & 0xFF; pos++; int len = data[pos] & 0xFF; pos++; if ((len & 0x80) != 0) { // 如果长度字节的最高位是1,表示后面跟着的是多字节长度 len &= 0x7F; for (int i = 0; i < len; i++) { len <<= 8; len |= data[pos] & 0xFF; pos++; } } byte[] value = new byte[len]; System.arraycopy(data, pos, value, 0, len); pos += len; TLV tlv = new TLV(tag, value); tlvList.add(tlv); } return tlvList; } /** * TLV对象 */ public static class TLV { private int tag; private byte[] value; public TLV(int tag, byte[] value) { this.tag = tag; this.value = value; } public int getTag() { return tag; } public byte[] getValue() { return value; } @Override public String toString() { return "TLV{" + "tag=" + tag + ", value=" + bytesToHexString(value) + '}'; } } /** * 将字节数组转换为十六进制字符串 * @param bytes 字节数组 * @return 十六进制字符串 */ public static String bytesToHexString(byte[] bytes) { StringBuilder sb = new StringBuilder(); for (byte b : bytes) { sb.append(String.format("%02X", b)); } return sb.toString(); } } ``` 使用示例: ```java public class Test { public static void main(String[] args) { byte[] data = TLVUtils.encode(0x01, new byte[]{0x01, 0x02, 0x03}); System.out.println(TLVUtils.bytesToHexString(data)); List<TLVUtils.TLV> tlvList = TLVUtils.decode(data); for (TLVUtils.TLV tlv : tlvList) { System.out.println(tlv.toString()); } } } ``` 输出结果: ``` 0103010203 TLV{tag=1, value=010203} ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值