1、定义tld文件
2、标签实现
/** * Description: 下拉框选择标签 * Created by Hoscen on 2019/5/20 20:37 with IntelliJ IDEA. */ public class SelectTag extends BodyTagSupport { private String id; private String clasz; private String name; private String title; ... 此处省略一些属性以及set、get方法 @Override public int doStartTag() throws JspException { HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest(); request.setAttribute("tag", this); try { startTag(request); } catch (Exception e) { LOGGER.error("SelectTag exception",e); } return EVAL_BODY_INCLUDE; } @Override public int doEndTag() throws JspException { HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest(); try { endTag(request); } catch (Exception e) { LOGGER.error("SelectTag excepion",e); } return EVAL_PAGE; } private void startTag(HttpServletRequest request) throws Exception { JspWriter out = this.pageContext.getOut(); SelectTag tag = (SelectTag) request.getAttribute("tag"); out.write("xxx"); // 后台拼接html输出 .... // 此处省略 } private void endTag(HttpServletRequest request) throws Exception { JspWriter out = this.pageContext.getOut(); out.write("xxx"); .... // 此处省略 } }
3、web.xml配置jsp-config
4、在jsp中应用
5、效果
6、总结
通过自定义标签我们可以将常用的UI组件做一个封装,好处如下:
1)使用简单清爽,只需一行代码;
2)所有页面统一使用,后期修改组件只需要修改标签体