Pergunta

I want to create a custom component in JSF and have created it already.Now I want to create attributes for that custom tag that i use in the XHTML file and make them as mandatory. I have created a component MyJSFComponent extending from UIOutput class. How can i mandate certain attributes?

Foi útil?

Solução

You don't do that in the UIComponent side, but in the .taglib.xml or TagHandler side.

In the .taglib.xml file you can just add a <required>true</required> entry to the attribute.

<attribute>
    <name>foo</name>
    <required>true</required>
    <type>java.lang.String</type>
</attribute>

You're however dependent on the tooling (the editor) whether this will cause an error or not. JSF/Facelets namely won't check it during runtime. Eclipse for example will automatically inline the attribute when autocompleting the tag in the editor, however it's possible to remove it afterwards and it'll run without errors.

A more solid enforcement is using a ComponentHandler class which offers the getRequiredAttribute() method which would throw TagException when absent. You can then register this handler in .taglib.xml file as follows:

<component>
    <component-type>com.example.SomeComponent</component-type>
    <handler-class>com.example.SomeComponentHandler</handler-class>
</component>

Whereby the handler class basically look like this:

public class SomeComponentHandler extends ComponentHandler {

    public SomeComponentHandler(ComponentConfig config) {
        super(config);
        getRequiredAttribute("foo");
    }

}

This does a real runtime check on the presence of the attribute.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top