alehro
alehro

Reputation: 2208

How to validate bean property injected with @ManagedProperty without xml?

I've found a lot of topics discussing how to inject property but none of them suggests validation method. Here is my bean:

@ManagedBean
@RequestScoped
public class MyBean {       
    @ManagedProperty(value = "#{param.key}")
    private String keyFromUser;
}

Currently if param.key is missing among GET params I have

com.sun.faces.mgbean.ManagedBeanCreationException: An error occurred performing resource injection on managed bean myBean

Upvotes: 0

Views: 303

Answers (2)

BalusC
BalusC

Reputation: 1109532

Use <f:viewParam> instead. It's like <h:inputText>, but then for GET request parameters. It thus allows for registering validators by validator attribute or even <f:validator> and <f:validateXxx> tags. You can even attach a <h:message> to it.

<f:metadata>
    <f:viewParam id="key" name="key" value="#{myBean.keyFromUser}" validator="myValidator" />
</f:metadata>
<h:message for="key" />

You only need to move the @PostConstruct job to <f:event type="preRenderView">.

See also:

Upvotes: 2

Karl Kild&#233;n
Karl Kild&#233;n

Reputation: 2435

I have used JSF-beans pretty little so I must say I don't understand your functional requirement. Perhaps annotate a method @PostConstruct and do validation there? That's were I put stuff that needs to be done after depedency injection is resolved

As a side note that does not answer the question directly I think CDI is very strong for scenarios like this.

Would look something like:

@Inject
@RequestParam (validator = MyValidator.class)

if you are interested I can supply the actual full implementation

Upvotes: 1

Related Questions