user6492999
user6492999

Reputation: 135

Update form input before submit

I'm developing JSF web application and have some HOW-TO questions. I have the following use-case scenario:

  1. User types text, using h:inputText
  2. then clicks submit
  3. Value from above h:inputText is encrypted on the client side (using JavaScript)
  4. Form is submitted with encrypted value
  5. h:inputText value is restored to previous value (typed by user, not encrypted).

I would like to send encrypted values in generic way. It should be transparent for user. I would like to have a mechanism to mark "encrypt-ready" fields using html attribute eg. encrypt="true".

Data have to be encrypted on the client side because server can't see it in RAW form.

Thanks in advance.

Upvotes: 1

Views: 642

Answers (1)

Alex Fire
Alex Fire

Reputation: 707

Here is an example how it could work with jQuery:

<h:head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</h:head>
<h:body>
    <script>
        $(function() {

            $("form").submit(function() {
                $("input[data-encrypt='true']").each(function() {
                    $(this).val(encrypt($(this).val()));
                });
            });

            $("input[data-encrypt='true']").each(function() {
                if ($(this).val()) {
                    $(this).val(decrypt($(this).val()));
                }
            });
        });

        function decrypt(str) {
            // to be implemented
            return "decrypted value";
        }

        function encrypt(str) {
            // to be implemented
            return "encrypted value";
        }
    </script>


    <h:form id="form">
        <h:inputText value="#{viewBean.value}" id="val" pt:data-encrypt="true" />
        <h:commandButton value="Process" />
    </h:form>
</h:body>

You could extract the javascript part in an own .js file and include it in any page you need. Don't forget to define pt namespace:

xmlns:pt="http://xmlns.jcp.org/jsf/passthrough"

This solution is not working with f:ajax.

Upvotes: 1

Related Questions