6

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?

reevesy
  • 3,452
  • 1
  • 26
  • 23
Kristal
  • 235
  • 2
  • 3
  • 9

2 Answers2

13

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>
Siva Charan
  • 17,940
  • 9
  • 60
  • 95
4

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');
      }
    });
    
elrado
  • 4,960
  • 1
  • 17
  • 15
  • I don't know ajax so, there is no another way other than form? – Kristal Mar 03 '12 at 19:38
  • 1
    @Kristal You just have to send data from client to server :). Either submit whole page or just par of it, but you have to submit something. If you don't line input:submit just use javascript function document.forms["myform"].submit(); – elrado Mar 03 '12 at 19:47