views:

341

answers:

1

I have a page with link http://localhost:8080/Test/Page.faces?id=asdasdasd The page got 2 text field and one button, after user key in the details and click submit, it works well when you first time click the submit button, the id will return me the exact value, but if the user never enter the value and click submit the validation will be invoked and next click the button again the id return null? How to solve this problem anyone can help?

A: 

Yes, when the user clicks on the button, the browser does a new request to the server. That new request doesn't have the ?id=asdasdasd as part of it. The easiest solution I can think of is to store that value into a hidden text field on the page. You can use some javascript to populate the value.

So, if you have a <h:hidden id="idHidden" value="#{mybean.idHidden}"/> on your JSP, maybe some javascript like this:

<script type='text/javascript'>      
  function gup( name )
  {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null )
      return "";
    else
      return results[1];
  }

  if(gup('id') != "") {
     document.forms[0].idHidden.value = gup('id');
  }

</script>

I haven't checked this code for errors, but the idea is the first time the page loads, the value of 'id' is stored in a hidden input field. That field is bound to your managed bean so the value is persisted across page refreshes. Just reference the id value stored on the bean (as idHidden in the example above) instead of the request parameter.

BTW: I stole the GUP function from http://www.netlobo.com/url_query_string_javascript.html

Nick

Nicholas Smith