1

This is my jsp page.

Code of jsp page :-

<img src='image.jpg' height=200px width=200px>
<form action="buyserv">
<%
ArrayList al=new ArrayList();
al.add("naman");
al.add("gupta");
request.setAttribute("allproducts", al);
RequestDispatcher rd = request.getRequestDispatcher("/buyserv");
rd.forward(request, response);

%>
<input type="submit" value="Buy"></form> 
<a href="ShowAllProducts.jsp"><input type="button" value="Continue"></a> 

I want that on clicking Buy button,the arraylist (al) should be passed to buyserv(servlet). However the list is getting passed to buyserv but the problem is that the jsp page is not getting displayed.But I want to display the jsp page as well as pass the arraylist on button click. Can anyone tell me how can I do so ?

Code of buyserv :-

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws   
ServletException, IOException 
{
ArrayList al=(ArrayList)request.getAttribute("allproducts");
PrintWriter out=response.getWriter();
out.print(al.get(0));
}
1
  • Why would you want to pass a hardcoded list from JSP to a servlet? If the list is harcoded, it ought to be hardcoded in a class accessible to both to begin with. Commented Apr 14, 2014 at 19:23

1 Answer 1

1

You can pass a list as String[] in the following way:

<form action="buyserv">
<input type='text' name='list'  value='a' />
<input type='text' name='list'  value='b' />
<input type='text' name='list'  value='c' />
<input type="submit" value="Buy" />
</form> 

You could also use type='hidden' if you don't want the values visible on the form.

In the servlet:

String[] values = request.getParameterValues("list");

If you need the values to be generated from a list, use a loop:

<form action="buyserv">
<%
  String[] array = { "a", "b", "c" };
  for(int i=0; i<array.length; i++)
  {
    out.print("<input type='text' name='list'  value='" + array[i] + "' />");
  }
%>
<input type="submit" value="Buy" />
</form> 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.