薛源少
薛源少

Reputation: 306

How to pass javascript variable in jsp page to another java file?

Good Evening, I try to do a checkbox which embedded in a JSP page. I use document.getElementByID("checkbox") in the JSP javascript function. How to pass the variables in the javascript function to another java file without passing it through url for security concern?

This is Checkbox Function:

var checkbox = document.getElementById("chbx");

 function foo(){
   if(checkbox.checked=true){
       //passThisVariableToAnotherJavaFile-isChecked
         }
   else {
        //passThisVariableToAnotherJavaFile-isNotChecked
         }
    };

This is Java File:

public class CheckBoxEvent{

if(isChecked) {
   //then whatever
} else if (isNotChecked) {
          //then no whatever
}

}

I am a newbie is this jsp stuff, I used to be doing this in PHP but everything mixed-up in my mind when there is a HashMap appear in the java file. Well, need some hints and help.

Thank You

Upvotes: 0

Views: 3134

Answers (2)

M Sach
M Sach

Reputation: 34424

when you do var checkbox = document.getElementById("chbx"); you are doing it at client side. Now if you want to propagate this value to server side i.e to some java class(most of the cases it will be servlets) then you have two options:-

1)Make an AJAX call. (You can also use jquery here to make AJAX call).Here is 

the small example, you can find ample on google

$.ajax({ 
type: 'GET', 
dataType: 'json', 
url: servlerURL, 
success: function(reply) { 

},
error: function (xhr, textStatus, errorThrown) { 

} 

});

or

2)Submit the form

Upvotes: 0

AllTooSir
AllTooSir

Reputation: 49432

How to pass the variables in the javascript function to another java file without passing it through url for security concern?

You have two options here and in both the cases you need to send the value to the server for processing :

  1. An AJAX POST or GET request. This looks more appropriate to your requirement. You can get an example here.
  2. Submit the form using POST.

Read here When do you use POST and when do you use GET?

In both the cases , there will be a Servlet/JSP/Controller handling the request in the server. You can call the methods in your Custom Java class with the request parameters.

Upvotes: 1

Related Questions