tags:

views:

68

answers:

2

Hi all,

How can I assign a value to a variable in a JSP page, on a button click?

I have a button "delete" in my JSP page. when a user clicks on this button it has to set a var (say a boolean flag or a string) to some value. How can I do this?

<% boolean del=false; %>
<input type="button" name="deleteAnswer" value="delete" onClick= <Code to set del> />
<% if(del) { My Code } %>
A: 

Web interfaces do not work like that unfortunately.

The whole JSP gets rendered first and sent to the browser. Then the user can click, and you can send the result to the server and make another page. There is no way the user can interact with the JSP while it is being processed on the server.

An alternative would be using JavaScript to react on the click.

Thilo
A: 

Server machine has a webserver with Java/JSP. Client machine has a webbrowser for HTML/CSS/JS. Webbrowser sends HTTP requests and retrieves HTTP responses. Webserver retrieves HTTP requests and sends HTTP responses. Java/JSP runs at the webserver and produces a HTML/CSS/JS page. Server machine sends HTML/CSS/JS page over network to client machine. Webbrowser retrieves HTML/CSS/JS and starts to show HTML, apply CSS and execute JS. There's no means of Java/JSP at client machine. To execute Java/JSP during a client action, you just have to attach specific Java/JSP code to specific HTTP requests.

To start, just have a HTML form something like this in the JSP:

<form action="delete" method="post">
    <input type="submit" value="Delete">
</form>

And define a Servlet in web.xml which listens on an url-pattern of /delete:

<servlet>
    <servlet-name>delete</servlet-name>
    <servlet-class>com.example.DeleteServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>delete</servlet-name>
    <url-pattern>/delete</url-pattern>
</servlet-mapping>

Create a com.example.DeleteServlet which look like this:

public class DeleteServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Your code here.

        // Show JSP page.
        request.getRequestDispatcher("page.jsp").forward(request, response);
    }
}

That's basically all. To learn more about JSP/Servlets, I can recommend those tutorials.

BalusC