I am learning JSF 2.2 and I am having a little trouble finding a good answer that i can understand as to how to have more for validation on a GET parameter.
I have a source.xhtml file that has a link it like this:
<h:link value="ALTER" outcome="/main/showSqlTemplates.xhtml">
<f:param name="type" value="ALTER" />
</h:link>
and in my destination.xhtml i have code that looks like this:
<f:metadata>
<f:viewParam id="type" name="type" value="#{showSqlTemplateManagedBean.type}" required="true" requiredMessage="Invalid page access. Please use a link from the menu."/>
</f:metadata>
<h:message for="type" class="bold"></h:message>
<br/>TYPE is : #{showSqlTemplateManagedBean.type}
and my bean class looks like this:
@ManagedBean
@RequestScoped
public class ShowSqlTemplateManagedBean {
String type = "";
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public ShowSqlTemplateManagedBean() {
}
}
as you can see i have used the "required" attribute to make sure the type parameter is at least there and everything is working fine as far as that goes. But i would like to do more validation.
Specifically I want to make sure the value of the String type will only be ALTER,INSERT,UPDATE OR DELETE.
Is this where a custom validator comes in? A custom validator seems to be over kill for such a simple validation check. I am sure I am missing something. Perhaps put something in the PostConstruct init() method?
Just make it an enum
.
@ManagedBean
@RequestScoped
public class ShowSqlTemplateManagedBean {
public enum Type {
ALTER, INSERT, UPDATE, DELETE;
}
private Type type;
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
}
JSF has a builtin converter for enumns which will kick in fully transparently. Any invalid value will cause a conversion error which you can customize via converterMessage
attribute of the <f:viewParam>
.
Enums have more benefits elsewhere in the code, too.
Unrelated to the concrete problem, explicitly initializing properties with an empty string (or even null
) is poor practice. Don't do that anymore. Moreover, initializing managed bean properties with a non-empty-string or non-null should happen in a @PostConstruct
annotated method.