[JAVA] What to do when the value becomes null in the second getSubmittedValue () in JSF Validator

environment OS : macOS Hight Sierra Version 10.13.2 Eclipse : Neon.3 Release (4.6.3) Java : JDK8 GlassFish : 4.1.2

Event: In JSF Validator, the value becomes null in the second getSubmittedValue ()

スクリーンショット 2018-01-16 21.25.39.png

inputPassword.xhtml(screen)


<abridgement>
  <h:outputLabel>Please enter the password.</h:outputLabel>
  <br />
  <h:inputSecret id="password" value="#{passwordBean.password}">
    <f:validateRequired />
    <f:validateLength minimum="3" maximum="10" />
    <f:validator validatorId="passwordValidator" />
    <f:attribute name="target" value="password" />
  </h:inputSecret>
  <h:message for="password" errorClass="error" />
  <br />
  <h:outputLabel>Already for confirmation&nbsp;&nbsp;Please enter it once.</h:outputLabel>
  <br />
  <h:inputSecret id="rePassword" value="#{passwordBean.kakuninPassword}">
    <f:validateRequired />
    <f:validator validatorId="passwordValidator" />
    <f:attribute name="target" value="rePassword" />
    <f:attribute name="passwordId" value="password" />
  </h:inputSecret>
  <h:message for="rePassword" errorClass="error" />
<abridgement>

PasswordValidator.java(Custom validator)


<abridgement>
@FacesValidator(value = "passwordValidator")
public class PasswordValidator implements Validator {
    /**Character strings that should not be used for passwords. */
    private static final String KINSHI = "password";
    /**The name of the name attribute that specifies the check target. */
    private static final String TARGET_KEY = "target";
    /**The value of the name attribute specified when checking the password. */
    private static final String TARGET_PASSWORD = "password";
    /**The value of the name attribute specified when checking the confirmation password. */
    private static final String TARGET_RE_PASSWORD = "rePassword";
    /**ID of password input field. */
    private static final String PASSWORD_ID_KEY = "passwordId";

    /*
     * (non-Javadoc)
     * @see javax.faces.validator.Validator#validate(javax.faces.context.
     * FacesContext, javax.faces.component.UIComponent, java.lang.Object)
     */
    @Override
    public void validate(FacesContext context, UIComponent component, Object value)
            throws ValidatorException {
        String target = (String) component.getAttributes().get(TARGET_KEY);
        if (TARGET_PASSWORD.equals(target)) {
            validatePassword(value);
        }
        if (TARGET_RE_PASSWORD.equals(target)) {
            validateRePassword(component, value);
        }
    }

    /**
     *Validate the password entered.
     * @param value input value.
     */
    private void validatePassword(Object value) {
        String inputedValue = (String) value;
        if (inputedValue.equals(KINSHI)) {
            FacesMessage errorMessage = new FacesMessage(KINSHI + "Cannot be used.");
            errorMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(errorMessage);
        }
    }

    /**
     *Validate the password re-entered for verification.
     * @param component {@link UIComponent}
     * @param value input value.
     */
    private void validateRePassword(UIComponent component, Object value) {
        String rePassword = (String) value;
        String passwordId = (String) component.getAttributes().get(PASSWORD_ID_KEY);
        if (StringUtils.isNotBlank(passwordId)) {
            String password = getInputedPasswordValue(component, passwordId);
            if (StringUtils.isNotEmpty(rePassword)) {
                if (!rePassword.equals(password)) {
                    FacesMessage errorMessage = new FacesMessage("It does not match the password you entered.");
                    errorMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
                    throw new ValidatorException(errorMessage);
                }
            }
        }
    }

    /**
     *Get the password input value from the id attribute value of the input tag.
     * @param component {@link UIComponent}
     * @id attribute value of param id input tag.
     * @return password input value.
     */
    private String getPasswordValueById(UIComponent component, String id) {
        HtmlInputSecret inputTextConf = (HtmlInputSecret) component.findComponent(id);
        Object submittedValue = inputTextConf.getSubmittedValue();
        return submittedValue.toString();
    }
}

Pattern where the value is not null the second time: Error in the first validation

スクリーンショット 2018-01-16 21.42.57.png

スクリーンショット 2018-01-16 21.43.24.png

スクリーンショット 2018-01-16 21.43.54.png

スクリーンショット 2018-01-16 21.44.25.png

Pattern where the value becomes null the second time: Normal in the first verification

スクリーンショット 2018-01-16 21.45.27.png

スクリーンショット 2018-01-16 21.45.51.png

スクリーンショット 2018-01-16 21.46.46.png

Reason: Because the validation is finished and setSubmittedValue (null) is executed

image.png ** JSF Life Cycle **

  1. View restoration
  2. Apply input value
  3. Input value conversion and verification
  4. Bind the value to a variable in the backing bean
  5. Execution of processing
  6. Rendering the response

This time, getSubmittedValue () resulted in a null value when an error occurred in the first validation in 3 of this life cycle.

Details of JSF 2.0 | Kao Terada --Yoshio Terada For the second and subsequent requests (when you fill in the required items and press the button), after the UIView tree is restored (first in the life cycle), the request value application phase (second in the life cycle) ) Applies the input value to the UIComponent. (In this example, HtmlInput # setSubmittedValue () is executed.) This setSubmittedValue () value is fetched by getSubmittedValue () until the validation phase of the input value (third life cycle) is completed. I can. At the end of the input value validation phase, ** setSubmittedValue (null) is executed ** and HtmlInput # setValue (“foo”) is called for the input value, and in the following phases, the input value is HtmlInput # getValue ( ) Will be used to get **.

Action: Get the value with getValue () when the value becomes null with the second getSubmittedValue ()

<No corrections in other parts>
    private String getPasswordValueById(UIComponent component, String id) {
        HtmlInputSecret inputTextConf = (HtmlInputSecret) component.findComponent(id);
        Object submittedValue = inputTextConf.getSubmittedValue();
        if (submittedValue == null) {
            // getSubmittedValue()When the value becomes null with, getValue()Get the value with
            submittedValue = inputTextConf.getValue();
        }
        return submittedValue.toString();
    }
<No corrections in other parts>

スクリーンショット 2018-01-16 22.48.50.png

スクリーンショット 2018-01-16 22.52.31.png

スクリーンショット 2018-01-16 22.52.43.png

スクリーンショット 2018-01-16 22.53.01.png

Reference site: This is the way to set up a Validator with annotations.

-JSF validation-What DEN thinks

Recommended Posts

What to do when the value becomes null in the second getSubmittedValue () in JSF Validator
What to do when the changes in the Servlet are not reflected
What to do when IllegalStateException occurs in PlayFramework
What to do when rails db: seed does not reflect in the database
What to do when The SSL certificate has expired
What to do when JSF tags do not become HTML
What to do when a null byte error occurs
[React.useRef] What to do when the latest state cannot be referenced in the event listener
What to do when "Fail to load the JNI shared library" is displayed in Eclipse
What to do when it becomes Unable to find CDI BeanManager.
What to do when Method not found in f: ajax
What to do when Cannot format given Object as a Date in convertDateTime of JSF
[Rails Tutorial Chapter 2] What to do when you make a mistake in the column name
What to do when Rails on Docker does not reflect controller changes in the browser
What to do when javax.batch.operations.JobStartException occurs
What to do when an UnsupportedCharsetException occurs in a lightweight JRE
How to output the value when there is an array in the array
What to do if the Rails page doesn't appear in Rails tutorial 1.3.2
What to do if Cloud9 is full in the Rails tutorial
What to do if you forget the root password in CentOS7
[Rails] What to do when the error No database selected and Unknown database appears in db: migrate
What to do when you want to know the source position where the method is defined in binding.pry
What to do when javax.el.ELException: Not a Valid Method Expression: appears when the JSF screen is displayed
[IOS] What to do when the image is filled with one color
What I thought when passing the user input value to the Service class
What to do if the prefix c is not bound in JSP
What to do when a javax.el.PropertyNotWritableException occurs
What to do when Blocked Host: "host name" appears in Ruby on Rails
What to do and how to install when an error occurs in DXRuby 1.4.7
What I did when JSF couldn't display database information in the view
What to do if tomcat process remains when tomcat is stopped in eclipse
What to do if Operation not permitted is displayed when you execute a command in the terminal
Android development, how to check null in the value of JSON object
What to do when undefined method ʻuser_signed_in?'
Notes on what to do when a WebView ClassNotFoundException occurs in JavaFX 12
What to do when you think you can't do Groovy-> Java in IntelliJ IDEA CE
What to do if the changes are not reflected in the jar manifest file
[Grails] Error occurred running What to do when the Grails CLI does not start
Androd: What to do about "The Realm is already in a write transaction in"
What to do if ffi installation fails when launching an application in Rails
What to do if the server tomcat dies
When the server fails to start in Eclipse
What to do when debugging "Source not found"
What do you use when converting to String?
I want to get the value in Ruby
What to do when ‘Could not find’ in any of the sources appears in the development environment with Docker × Rails × RSpec
What to do if you get the warning "Uniqueness validator will no longer enforce case sensitive comparison in Rails 6.1." in Rails 6.0
What to do if you can't get the text of an element in Selenium
What to do when Address already in use is displayed after executing rails s
What to do if the debug gem installation fails
What to do if the Rails server can't start
What to do if ClassNotFoundException occurs when starting Tomcat
What should I do to reload the updated Dockerfile?
What to do when rails creates a 〇〇 2.rb file
Error ExecJS :: RuntimeUnavailable: What to do when it occurs
What to do if password authentication fails in Docker/Postgres
Null value is entered when assigning to an array
ParseException: What to do when Unparseable date is reached
What to do when Git Repository cannot be displayed in Team Explorer for Eclipse in Azure
What to do if you don't see the test code error message in the terminal console
[Rails] What to do if you accidentally install bundle in the production environment in your local environment