Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JSP with Buttons

Tags:

button

jsp

I have a button in a JSP page:

<button type="button" onclick="">Click me </button>  

I want to perform the following jsp code:

<% session.setAtrribute("status","guest"); %>  

when I press the button.

Is it possible to use JSP code on a button click and if yes how?

like image 368
Kristal Avatar asked Mar 03 '12 19:03

Kristal


People also ask

How can I tell if a button is clicked in JSP?

If you use a dot operator on a variable that is null, you get a null pointer exception. So you could use the dot operator on the string literal, and thus avoid explicitly checking for null: <% String x = request. getParameter("submit"); if("confirm".

Can we call JSP from HTML?

The client (webbrowser) will in turn execute the HTML/CSS/JS. Knowing this fact, it should be obvious that the only way to let JavaScript access/invoke some Java/JSP code is to send a HTTP request to the server side. This can be done in several ways: using window. location to do a synchronous GET request, or form.


2 Answers

Do something like this:-

    <% 
        if(request.getParameter("buttonName") != null) {
               session.setAttribute("status", "guest");
        }
    %>

    <FORM NAME="form1" METHOD="POST">
        <INPUT TYPE="HIDDEN" NAME="buttonName">
        <INPUT TYPE="BUTTON" VALUE="Button 1" ONCLICK="button1()">
    </FORM>

    <SCRIPT LANGUAGE="JavaScript">
        <!--
        function button1()
        {
            document.form1.buttonName.value = "yes";
            form1.submit();
        } 
        // --> 
    </SCRIPT>
like image 85
Siva Charan Avatar answered Nov 15 '22 11:11

Siva Charan


either use:

  1. <input type="submit" value="click"/> and set form action to some servlet/jsp page where you set you'r session attribute
  2. use ajax in onclick button method.

    JQUERY SAMPLE:

    $.ajax({
      url: "srvServlet", //or setJSP.jsp
      success: function(){
        alert ('ok');
      }
    });
    
like image 23
elrado Avatar answered Nov 15 '22 10:11

elrado