javascriptjavajspgetparameter

request.getParameter value not get data with spaces from value that user key in


I just learn jsp and Java and still new to it. I have this code in my a.jsp file.The user will need to enter any item in the value and click button Search.

<input type="text" value="" name="itemCode" id="itemCode">;
<input type="button" name="btnitemsearch" value="Search" onclick="searchItem();"> 

Then in the function searchItem(),

var code1 = document.getElementById("itemCode").value;
var getData = '../select_Item/b.jsp?itemCode=' + code1;

$(document).ready (function(){
     $("#openModalDialog").dialog({
         modal: true,
         autoOpen: false,
         title: "Item Search",
         width: 700,
         height: 400,
         });
     });

     $('#openModalDialog').dialog('open');
      $('#openModalDialog').load(getData);

So in b.jsp file, I use request get parameter to get the value but it only works if the value have no space.

<% String itemCode= request.getParameter("itemCode");
   System.out.println(itemCode);%>

Example if I enter value pencil of course it does print out "pencil". But if I enter value pencil 2b if only print out "pencil" without space " " and 2b.

I know that this question have been asked and duplicate.But in most of the question asked, the value use request.getParameter.It says that I need to surround the attribute value with quotes.

value="<%=request.getParameter("anything")%>"

But in my question is if the value have to be enter by the user.How to make it work ? Thank you.


Solution

  • Replace:

    var getData = '../select_Item/b.jsp?itemCode=' + code1;
    

    by

    var getData = '../select_Item/b.jsp?itemCode=' + encodeURIComponent(code1);
    

    You need to encode your query string to form a correct URL string.

    In this case: pencil 2b will become pencil%202b, and the space character is correctly preserved while accessing in your b.jsp