简体   繁体   English

如何验证不带xml的@ManagedProperty注入的bean属性?

[英]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 当前如果我有GET参数中缺少param.key

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

Use <f:viewParam> instead. 使用<f:viewParam>代替。 It's like <h:inputText> , but then for GET request parameters. 就像<h:inputText> ,但是对于GET请求参数。 It thus allows for registering validators by validator attribute or even <f:validator> and <f:validateXxx> tags. 因此,它允许通过validator属性甚至<f:validator><f:validateXxx>标签注册验证validator You can even attach a <h:message> to it. 您甚至可以在其上附加<h:message>

<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"> . 您只需要将@PostConstruct作业移动到<f:event type="preRenderView">

See also: 也可以看看:

I have used JSF-beans pretty little so I must say I don't understand your functional requirement. 我几乎没有使用过JSF-beans,所以我必须说我不理解您的功能要求。 Perhaps annotate a method @PostConstruct and do validation there? 也许注释方法@PostConstruct并在那里进行验证? 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. 作为一个不能直接回答问题的侧面说明,我认为CDI在这种情况下非常强大。

Would look something like: 看起来像:

@Inject
@RequestParam (validator = MyValidator.class)

if you are interested I can supply the actual full implementation 如果您有兴趣,我可以提供实际的完整实施

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM