Dan S.
Dan S.

Reputation: 177

How to use request.getParameterValues?

I'm trying to pass an array from one jsp page to another using a hidden form.

Here is the relevant code of my jsp files.

<td style="vertical-align: top;"><button onclick="getPlayerNames()"id="generate">Generate</button><br></td>


<form id="playerNames" method="post" action="lineups.jsp">
<input type="hidden" id="players" />
</form>

<script>
    function getPlayerNames(){
          var selected = document.querySelectorAll("#selected-players > tr > td");
          var playernames = [];
          for(var i=0; i<selected.length; ++i){
             //alert(selected[i].textContent);
             var num = (i-1)%6;
         if(num==0){
             playernames.push(selected[i].textContent);
         }


      }
      document.getElementById("players").values=playernames;
      alert(document.getElementById("players").values);
      document.getElementById("playerNames").submit();
}</script>

The alert message does show that the correct values are being placed in "players"

Then on my lineup.jsp I have:

<%String[] s = request.getParameterValues("players");
System.out.println(s[0]);%>

and I get a null pointer exception on the line with 'System.out.println(s[0]);'

Upvotes: 0

Views: 30995

Answers (3)

sbur
sbur

Reputation: 1

OK, s is null here hence s[0] throws NullPointerException

The method getParameterValues() will generally come into picture if there is a chance of getting multiple values for any input parameter, this method will retrieve all of it values and return it as string array.

but in your case I think you have only one value to fetch, use request.getAttribute and try to print the result i.e. s and not s[0]

once s is not null , you can go for s[0]

Upvotes: 0

Srinu Chinka
Srinu Chinka

Reputation: 1491

  1. name attribute is not specified to input tag, if name attribute not specified then no value will be sent.

  2. In your case request.getParameter and request.getParameterValues return same value because players element is specified only one. When you use request.getParameter it'll return direct string, request.getParameterValues will return string[] with length 1.

If you want to send multiple players and you don't want to repeat element in your jsp, then concat the players with some special character like the following:

document.getElementById("players").value=playernames.join("::");

You can get is as string in lineup.jsp and you can split it with the same special characters like the following:

<%
   String players = request.getParameter("players");
   String[] s = players.split("::");
%>

Upvotes: 3

RishikeshD
RishikeshD

Reputation: 189

String[] players = request.getParametervalues("nameOfTheHiddenField");

Please try specifying a name for the hidden field and it will work.

Upvotes: 1

Related Questions