简体   繁体   English

如何将参数从jsp页面传递到servlet?

[英]How to pass parameter from a jsp page to a servlet?

My problem is that I create an ArrayList in the servlet class filled by a form inside an html page. 我的问题是我在servlet类中创建了一个ArrayList,该类由html页面内的表单填充。 Then I pass my array-list to a jsp page that prints all the objects. 然后,我将数组列表传递给一个打印所有对象的jsp页面。 Now every object i printed becomes a "href" that calls the "doGet" method of the servlet. 现在,我打印的每个对象都变成了一个“ href”,它调用了servlet的“ doGet”方法。 I need to pass the index of the object selected by clicking on the link. 我需要通过单击链接来传递所选对象的索引。

//This is the implementation of the method doGet of my servlet: //这是我的servlet的doGet方法的实现:

//I know that is wrong to use getAttribute but I don't know what else could really work. //我知道使用getAttribute是错误的,但是我不知道还有什么可以真正起作用。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    **String ciao = request.getAttribute("id");** //this is the error
    int k = Integer.parseInt(ciao); // this is because i pass a String object and i'm already sure that it will be a number.
    String invio = lista.get(k);
    request.setAttribute("key", invio);
    RequestDispatcher dispatcher =
            getServletContext().getRequestDispatcher("/views/es3-item.jsp");
            dispatcher.forward(request, response);
    }

This is my jsp (es3-list.jsp) page that prints the objects: 这是我的jsp(es3-list.jsp)页面,用于打印对象:

<c:forEach  var="valore" items="${requestScope.message}" varStatus="theCount">//message is the key to pass the ArrayList "lista" to this jsp page.
<a href ="./es3"> <c:out value="${valore}"/> </a>
<a id="${theCount.index}"></a>
</c:forEach> 

you can Just append parameters to the request url . 您可以只将参数附加到请求url。 I see you are using doGet so its just that you can append parameters after question mark like 我看到您使用的是doGet,因此您可以在问号后附加参数,例如

myURL?param1=value1&param2=value2

The above case is with href of anchor tag. 以上是锚标签的href。 You will have to create href as above only. 您只需要如上所述创建href。 But this you can have form which will be submitted to doGEt like 但是,您可以将表单提交给doGEt,例如

<form action="myservlet">
<input type="text" name="param1"/>  
<input type="text" name="param2"/>      
 </form>

And from servlet in both cases you can access values as 在这两种情况下,都可以从servlet访问值,如下所示:

request.getParameter("param1");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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