Use constants in JSP to prevent hard coding

   The hard coding of jsp pages is a very troublesome problem. After working for so many years, I have seen many projects have this problem. Here is how to prevent the hard coding of pages.

     In Java programs, hardcoding can be avoided by means of static constants. If Scriptlet is allowed in JSP , of course, constants can also be used directly, but code such as <%%> is generally not allowed in JSP . For example, what should we do in JSTL ? We don't want to see code like this:

<c:if test=${state=='01'}>
</c:if>

 

The following describes how to use JspTag to deal with it:

 

The first step is to create the my-tag.tld description file under /WEB-INF/tld/ :

Note: According to the JSP2.1 specification, the tld file cannot be stored in the /WEB-INF/classes or /WEB-INF/lib directory, especially in the /WEB-INF/tags directory or subdirectory, otherwise an error will occur:
 exception:org.apache.jasper.JasperException: PWC6180: Unable to initializeTldLocationsCache
 root cause:org.apache.jasper.JasperException: PWC6336: Illegal TLD path/WEB-INF/tags/fn.tld,  must not start  with “/WEB- INF/tags" does not have this problem
 in
Tomcat and Weblogic , GlassFish strictly follows the specification and can place the tld file in the /WEB-INF/tld directory.

<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns=" http://java.sun.com/xml/ns/j2ee "
xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "
xsi:schemaLocation=" http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd "
version="2.0">
    <description>my tag</description>
    <display-name>my tag</display-name>
    <tlib-version>1.0</tlib-version>
    <short-name>my-tag</short-name>
    <uri>/my-tag</uri>
    <tag>
    <!--
        Initialize the MyConstant constant in JSP for reference in JSTL.
        Example of use in jsp: <my-tag:MyConstant var="constant name"/>
        Required parameter var: specify to initialize a variable in MyConstant, if it is empty, an exception will be reported
        Optional parameter scope: variable scope, default is page
   -->
        <description>MyConstant常量</description>
        <name>MyConstant</name>
        <tag-class>com.test.util.tag.MyConstantTag</tag-class>
        <body-content>JSP</body-content>
        <attribute>
            <description>Required parameter var: specify to initialize a variable in MyConstant, if it is empty, an exception will be reported</description>
            <name>var</name>
            <required>true</required>
            <rtexprvalue>true</rtexprvalue>
         </attribute>
        <attribute>
            <description>Variable scope (default is page)</description>
            <name>scope</name>
            <required>false</required>
            <rtexprvalue>true</rtexprvalue>
         </attribute>
    </tag>
</taglib>

 

 

The second step, create JAVA processing code com.test.util.tag.MyConstantTag 

It inherits TagSupport and rewrites the doStartTag() method, so that the constants in java can be used directly in JSP :

 

public class MyConstantTag extends TagSupport {
    private static final long serialVersionUID = 3258417209566116146L;
    private final Log log = LogFactory.getLog(MyConstantTag.class);
    public String clazz = MyConstant.class.getName();
    protected String scope = null;
    protected String var = null;
    public int doStartTag() throws JspException {
        Class c = null;
        int toScope = PageContext.PAGE_SCOPE;
        if (scope != null) {
            toScope = getScope(scope);
        }
        try {
            c = Class.forName(clazz);
        } catch (ClassNotFoundException cnf) {
           log.error("ClassNotFound - maybe a typo?");
            throw new JspException(cnf.getMessage());
        }
       try {
            if (var == null || var.length() == 0) {
                throw new JspException("Constant parameter var must be filled in!");
            } else {
                try {
                    Object value = c.getField(var).get(this);
                    pageContext.setAttribute(c.getField(var).getName(), value, toScope);
                } catch (NoSuchFieldException nsf) {
                    log.error(nsf.getMessage());
                    throw new JspException(nsf);
                }
            }
         } catch (IllegalAccessException iae) {
            log.error("Illegal Access Exception - maybe a classloader issue?");
            throw new JspException(iae);
        }
     return (SKIP_BODY);
}
/**
* @jsp.attribute
*/
    public void setScope(String scope) {
        this.scope = scope;
    }
    public String getScope() {
        return (this.scope);
    }
/**
* @jsp.attribute
*/
    public void setVar (String var)
        this.var = var;
     }
    public String getVar() {
        return (this.var);
    }
/**
* Release all allocated resources.
*/
    public void release() {
        super.release();
        clazz = null;
        scope = MyConstant.class.getName();
    }
    private static final Map scopes = new HashMap();
        static {
            scopes.put("page", new Integer(PageContext.PAGE_SCOPE));
            scopes.put("request", new Integer(PageContext.REQUEST_SCOPE));
            scopes.put("session", new Integer(PageContext.SESSION_SCOPE));
            scopes.put("application", new Integer(PageContext.APPLICATION_SCOPE));
        }
        public int getScope(String scopeName) throws JspException {
            Integer scope = (Integer) scopes.get(scopeName.toLowerCase());
        if (scope == null) {
            throw new JspException("Scope '" + scopeName + "' not a valid option");
        }
        return scope.intValue();
     }
}

 

     Create the constant class MyConstant:

package cn.hshb.common;

public final class MyConstant {

	public static String STATE_01 = "1";
	
	
}

 

 

 

The third step, configure <jsp-config/> in web.xml :

<jsp-config>
    <taglib>
        <taglib-uri>/my-tag</taglib-uri>
        <taglib-location>/WEB-INF/tld/my-tag.tld
        </taglib-location>
    </taglib>
</jsp-config>

 

 

The fourth part, JSPheader introduction:

<%@ taglib prefix="my-tag" uri="/my-tag" %>
<my-tag:MyConstant var="STATE_01"/>

 

Constants are now available with ${STATE_01} .

Let's look at the difference from the original hardcoding :

<c:if test=${state==STATE_01}>

</c:if>

 

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326932515&siteId=291194637