Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass parameter from jsp to servlet

Tags:

java

jsp

servlets

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());
like image 676
Patriotic Avatar asked Dec 04 '22 05:12

Patriotic


2 Answers

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>
like image 197
developerwjk Avatar answered Dec 06 '22 19:12

developerwjk


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">
like image 40
ricardoorellana Avatar answered Dec 06 '22 20:12

ricardoorellana