JSF 1.2 custom component from jsp:include

2019-02-27 12:34发布

问题:

Before I get started with my question, here are my unfortunate limitations:

  1. I'm using JSF 1.2, not 2; so no composite component.
  2. I'm using JSP for rendering instead of facelets; so none of those composite components either.
  3. I'm not allowed to use any 3rd-party tag libraries (richFaces, iceFaces, etc.)

These limitations are set in stone.

Now moving onto my question. Currently, we have a JSP subview which handles creating an address. There is a lot of javascript that goes along with this, along with a backing bean. This page is never used directly. Instead, it's included using a <jsp:include />.

However, there are several attributes that I want to be able to change. For instance, is county required, are we currently doing address scrubbing, etc. In order to do this, it would make sense to use a custom component (I think?). However, I'm not really sure the best way to do this.

If I could, I would simply turn this JSP into a composite component and be done with it. However, that's not really an option based on my limitations.

What are my options? This wouldn't be so difficult if it weren't for the amount of javascript involved. I know my explanation was vague; however, I'm looking more for guidance than a direct answer. I've googled for things such as custom JSF 1.x components with javascript, etc. I haven't found many good articles, however.

Thanks in advance.

回答1:

Create a JSP tag file.

/WEB-INF/tags/foo.tag

<%@ tag body-content="empty" %>
<%@ attribute name="countryRequired" required="false" type="java.lang.Boolean" %>
<%@ attribute name="showAddress" required="false" type="java.lang.Boolean" %>

<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core" %>
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<h:panelGrid columns="2">
    <h:outputLabel for="country" value="Country" />
    <h:inputText id="country" value="#{bean.country}" required="${countryRequired}" />

    <c:if test="${showAddress}">
        <h:outputLabel for="address" value="Address" />
        <h:inputText id="address" value="#{bean.address}" />
    </c:if>
</h:panelGrid>

Declare and use it as follows (no additional XML configuration necessary):

<%@ taglib prefix="my" tagdir="/WEB-INF/tags" %>
...
<my:foo showAddress="true" />

Note that JSTL is also here a "view build time" tag like as in Facelets. Also note that you can't use #{} to reference JSP tag attributes.