JSF outputlabel clear

♀尐吖头ヾ 提交于 2020-01-16 16:49:10

问题


I have the following problem. I use a form when I provide only PIN. I have validator which checks if its a 4-digit number. Then the action on submit is set to the method which checks if the PIN exists in the database. If not it does message = "no PIN"; I used the message in the output label below the form. Previously it was null so there was no message there. Now it changes into "no PIN" but I have to clear it after clicking the submit button again because the error message doesn't disappear when you enter for example "12as" PIN and validator takes care of it. How should i implement such situation? Maybe using an output label in such situtation is a wrong idea?


回答1:


You can use JSF message component outside a validator: For a message for your input in your form:

 <h:message for="PIN"/> 

And at your managed bean you can add a FacesMessage using:

FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN,"No pin summary message","No pin detail message");
FacesContext.getCurrentInstance().addMessage("PIN", message);

No need to use a outputLabel here.




回答2:


You should not perform validation in action method. You should use a real validator.

Just implement the Validator interface accordingly. E.g.

@FacesValidator("pinValidator")
public class PinValidator implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        String pin = (String) value;

        if (pin == null || pin.isEmpty()) {
            return; // Let required="true" deal with it if necessary.
        }

        if (!pin.matches("\\d{4}")) {
            throw new ValidatorException(new FacesMessage("PIN must be 4 digits"));
        }

        if (!somePinService.exists(pin)) {
            throw new ValidatorException(new FacesMessage("PIN is unknown"));
        }    
    }

}

Use it as follows:

<h:outputLabel for="pin" value="PIN" />
<h:inputText id="pin" value="#{bean.pin}" validator="pinValidator" />
<h:message for="pin" />

The faces message of the validator exception will end up in the <h:message> associated with the component on which the validator is been fired.

If you're using ajax to submit the form, don't forget to make sure that the message is also taken into account on ajax render.


Unrelated to the concrete problem, the JSF <h:outputLabel> generates a HTML <label> element which is intented to label a form element (e.g. <input>, <select>, etc). It's absolutely not intented to show an arbitrary piece of text such as a validation message. I recommend to put JSF aside for now and start learning basic HTML. This way you will understand better which JSF components to pick to get the desired HTML output.



来源:https://stackoverflow.com/questions/16491317/jsf-outputlabel-clear

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!