5

how to pass a parameter from jsp to servlet using form which is not belong to any field of form without using session.i think code may be look like below example but doesn't work for me.plz help me.

in index.jsp:-

<form method="Post" action="servlet"> <input type="text" name="username"> <input type="password" name="password"> <% int z=1; request.setAttribute("product_no", z);%> <input type='submit' /> </form> 

in servlet.java:-

 int x=Integer.parseInt(request.getAttribute("product_no").toString()); 

2 Answers 2

10

Your form needs to be submitted, e.g. have a submit button. And you need to have your parameter as an input. Calling request.setAttribute inside the form doesn't do anything. Setting a request attribute is for when you are going to use a dispatcher to forward the request, not when you are using a form.

<% int z=1; %> <form method="Post" action="servlet"> <input type="text" name="username" /> <input type="password" name="password" /> <input type="hidden" name="product_no" value="<%=z%>" /> <input type='submit' /> </form> 
Sign up to request clarification or add additional context in comments.

3 Comments

but if i wants to pass a parameter when form is submitted instead of using any input field. how should i do this?
@user3751576, That question doesn't make sense to me. What are you trying to ask? What's the real goal here?
i get it. thnx. so, to pass a value through a form we have to use an input field. i think now i am right.
8

You can receive the parameters you submit in the form with the method:

request.getParameter("fieldname"); 

For intance, your servlet could get all the fields:

 @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username= request.getParameter("username"); String password= request.getParameter("password"); } } 

You can also send parameters from a link, e.g:

<a href="Servlet?nameOfParameter=valueOFparameter"> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.