简体   繁体   中英

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

Your form needs to be submitted, eg 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>

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, eg:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM