简体   繁体   中英

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

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.

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 ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM