package com; import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspTagException; import javax.servlet.jsp.tagext.BodyTagSupport; @SuppressWarnings("serial") public class OptionsTag extends BodyTagSupport { @Override public int doStartTag() throws JspException { return EVAL_BODY_INCLUDE; } @Override public int doEndTag() throws JspException { try { StringBuffer results = new StringBuffer(""); if ("SEX".equals(collection)) { results.append("<option value=\"0\" selected=\"selected\">请选择</option>"); results.append("<option value=\"1\">男</option>"); results.append("<option value=\"2\">女</option>"); } pageContext.getOut().write(results.toString()); } catch (IOException ex) { throw new JspTagException("错误"); } return EVAL_PAGE; } // collection只是传递一个标识,具体下拉值内容是从数据库取还是从请求中得到为不同具体实现 protected String collection; public String getCollection() { return collection; } public void setCollection(String collection) { this.collection = collection; } }
具体你的字典数据从数据库中如何存储如何查询,可以自定义实现
显示的标签实现,为了将来可以在页面取到标签内容值,我们定义隐藏域来保存属性值,然后在显示显示内容
package com; import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspTagException; import javax.servlet.jsp.tagext.BodyTagSupport; @SuppressWarnings("serial") public class SelectDisplay extends BodyTagSupport { @Override public int doStartTag() throws JspException { try { StringBuffer results = new StringBuffer(""); pageContext.getOut().write(results.toString()); } catch (IOException ex) { throw new JspTagException("错误"); } return EVAL_BODY_INCLUDE; } @Override public int doEndTag() throws JspException { try { StringBuffer results = new StringBuffer(""); if ("SEX".equals(collection)) { results.append("<span>"); results.append("<input type=\""); results.append("hidden\" name=\""); results.append(getName()); results.append("\""); results.append(" value=\""); results.append(getValue()); results.append("\">"); if ("1".equals(getValue())) { results.append("男"); } else if ("2".equals(getValue())) { results.append("女"); } else { results.append("请选择"); } results.append("</span>"); } pageContext.getOut().write(results.toString()); } catch (IOException ex) { throw new JspTagException("错误"); } return EVAL_PAGE; } // collection只是传递一个标识,具体下拉值内容是从数据库取还是从请求中得到为不同具体实现 protected String collection; // 传递的值 protected String value; // 该属性的名称 protected String name; public String getCollection() { return collection; } public void setCollection(String collection) { this.collection = collection; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
5.JSP中引用,直接在index.jsp中引用
需要引入相应的标签内容,引入的方式在JSP头部引用
标签的属性可以设置也可以不设置,标签的使用和HTML标签的使用是一样的,定义属性即可