0

I'm new to JSP, and trying to make the transition from ASP.NET (which is quite different).

I've basically got a set of html input buttons. Each of these buttons should redirect to the same page when pressed. However, I would like to pass a parameter too, i.e. I would want the page to behave differently based on which button initiated the redirection.

What I've done so far is to wrap the buttons in a form, which communicates with a servlet's GET method. From here, I can see which button was pressed.

I would now like to redirect to the page and also pass the value of the button which was pressed. How can this be done? The page I need to redirect to is a JSP page.

My code:

HTML page:

<form action="DashboardServlet" method="get">
<input type="button" value="Button1" name="button1"/>
<input type="button" value="Button2" name="button2"/>
</form>

DashboardServlet

....

    // If-statements to see what button was pressed

....

EDIT: I was thinking of using a session to store the value. Would this be valid?

4

1 に答える 1

1
request.getParameter("button1");

It works pretty much similar to what you use in case of textboxes.

To check which buttons was pressed: -

if (request.getParameter("button1") != null) {
    // button1 was pressed

} else if (request.getParameter("button2") != null) {
    // button2 was pressed
}

When you are redirecting the request to your JSP page, you can add those parameters to the request. The same request parameters won't be available in your JSP, untill you add it explicitly.


If you are using: - RequestDispatcher.forward(), then you can set the parameters in request: -

request.setAttribute("button1", request.getParameter("button1").toString());

and then: -

getServletContext().getRequestDispatcher("/yourJSP.jsp").forward()

And in your JSP, use: -

request.getAttribute("button1");

Or, if you are using response.sendRidirect, you can add your values to the queryString: -

String buttonValue = request.getParameter("button1").toString();
response.sendRedirect("/yourJSP.jsp?button1=" + buttonValue);
于 2012-11-20T19:23:27.427 に答える