Reputation: 848
I have a simple java bean which uses request parameters for property initialization. For this, seam provides a convenient @RequestParameter
annotation which injects the request parameter directly in a bean property which is great except for error handling. Is there any way to catch parsing exceptions (NumberFormatException
, ...) if the request parameters are broken to provide a more user friendly error output?
I'm aware of exception handling in pages.xml but I don't want to put a NumberFormatException
there, as it is way to generic without further context.
Minimal example for a bean, where parsing exceptions for entityId
should be caught:
@Name("apiPresenter")
@Scope(ScopeType.PAGE)
public class MyBean {
@RequestParameter
private Long entityId;
...
}
Upvotes: 1
Views: 166
Reputation: 4844
@RequestParameter
is handy sometimes but is not very flexible. When you need to map parameters that require conversion and/or validation, it is adviced to use page parameter definitions, as these let you specify a JSF converter or validator to apply during parameter decoding, for example:
<page view-id="/myview.xthml">
<param name="entityId" value="#{apiPresenter.entityId}" converterId="javax.faces.Long" />
</page>
If there are conversion or validation errors, the converter adds a message to the JSF FacesMessages component, which can be used to render the error condition in an error page. Note that you can use your own converters and/or validators here, you can even indicate that a parameter is required, as in:
<page view-id="/myview.xhtml">
<!-- parameter is required, issue error if it is not provided -->
<param name="entityId" value="#{apiPresenter.entityId}" validatorId="your.validator" required="true" />
</page>
Alternatively, you can use @RequestParameter
to assign the parameter to a String variable and then perform the conversion (and eventual redirection to an error page) by hand.
Upvotes: 1