Patriotic
Patriotic

Reputation: 2300

pass parameter from jsp to servlet

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());

Upvotes: 5

Views: 56559

Answers (2)

ricardoorellana
ricardoorellana

Reputation: 2340

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">

Upvotes: 8

developerwjk
developerwjk

Reputation: 8659

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>

Upvotes: 10

Related Questions