Reputation: 1235
I want to pass input data with a href instead of a button. The problem is I am sending an array, my for loop the input data is being stored so It creates multiple links. What is the course of action to take to fix this.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Firstjsp</title>
</head>
<body>
<% String locations[] = {"Loan 1", "33.890542", "151.274856", "Address 1","true", "-35404.34"};
for (int i =0; i<locations.length; i++)
{
%>
<form name="submitForm" method="POST" action="Mapper.jsp">
<Input type = "Hidden" name = "loc" value = "<%= locations[i] %>">
<A HREF="Mapper.jsp">View Map</A>
</form>
<%
}
%>
</body>
</html>
Upvotes: 0
Views: 2709
Reputation: 1108762
The HTTP request query string takes the form of name1=value1&name2=value2&name3=value3
. So all you need to do is converting the String[]
to a String
in exactly that format. Additional requirement is to use URLEncoder
to encode the names and values so that any special characters are been converted to %nn
format for proper usage in URLs.
This should do:
StringBuilder builder = new StringBuilder();
for (String location : locations) {
if (builder.length() > 0) builder.append("&");
builder.append("loc=").append(URLEncoder.encode(location, "UTF-8");
}
String locationsQuery = builder.toString();
Then you can specify it in the link as follows:
<a href="Mapper.jsp?<%=locationsQuery%>">View Map</a>
How to obtain it in the other side has already been answered in your previous question.
Unrelated to the concrete problem, writing raw Java code in JSPs is officially discouraged since a decade. You can achieve the same on a more easy manner with JSTL <c:url>
, <c:param>
and <c:forEach>
. Here's a kickoff example assuming that you've done a request.setAttribute("locations", locations)
in your preprocessing servlet or in top of JSP:
<c:url value="Mapper.jsp" var="mapperURL">
<c:forEach items="${locations}" var="loc">
<c:param name="loc" value="${loc}" />
</c:forEach>
</c:url>
<a href="${mapperURL}">View Map</a>
Upvotes: 2