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

时间:2015-03-31 11:59:05

标签: java jsp servlets

我的问题是我在由html页面内的表单填充的servlet类中创建了一个ArrayList。 然后我将我的数组列表传递给打印所有对象的jsp页面。 现在我打印的每个对象都变成了一个“href”,它调用了servlet的“doGet”方法。 我需要通过点击链接传递所选对象的索引。

//这是我的servlet的方法doGet的实现:

//我知道使用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);
    }

这是我打印对象的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> 

1 个答案:

答案 0 :(得分:1)

您只需将参数附加到请求网址即可。我看到你正在使用doGet,只是你可以在问号之后添加参数,如

myURL?param1=value1&param2=value2

以上情况是使用锚标记的href。您只需要创建如上所述的href。 但是你可以将表格提交给doGEt,如

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

在两种情况下,从servlet可以访问值

request.getParameter("param1");
相关问题