Java 将参数从jsp传递给servlet
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26497375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pass parameter from jsp to servlet
提问by Patriotic
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.
如何在不使用会话的情况下使用不属于任何表单字段的表单将参数从 jsp 传递到 servlet。我认为代码可能类似于下面的示例,但对我不起作用。请帮助我。
in index.jsp:-
在 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:-
在 servlet.java 中:-
int x=Integer.parseInt(request.getAttribute("product_no").toString());
采纳答案by developerwjk
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.
您的表单需要提交,例如有一个提交按钮。并且您需要将参数作为输入。request.setAttribute
在表单内部调用不会做任何事情。设置请求属性是为了当您打算使用调度程序转发请求时,而不是在您使用表单时。
<% 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>
回答by ricardoorellana
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:
例如,您的 servlet 可以获得所有字段:
@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">