jsp - Call Servlet and invoke Java code from JavaScript along with parameters -
I have a session key that is a JavaScript variable that I received from a REST API call. I have to call my Java code in servlet and pass that key as a parameter
In many ways:
-
Use
window.locationto set a GET request. The warning is that it is synchronous (hence the customer current page Will see changing).window.location = "http://example.com/servlet?key=" + encodeurIComponentbefore requesting the parameter to the request parameter Note the importance of the built-in
encodeurIComponent ()function to convert into words. -
Use
form.submit ()to fire the GET or POST request. The warning is also that it is synchronous.document.formname .key.value = key; Document.formname.submit ();& lt; Form name = "formname" action = "servlet" method = "post" & gt; & Lt; Input type = "hidden" name = "key" & gt; & Lt; / Form & gt;Alternatively, you can also just set the hidden area of an existing form and wait for the user to submit it.
-
Use
XMLHttpRequest # send ()An asynchronous request in the fire (also known as Ajax) to fire. Example below servlet "sdoGet ().var xhr = new XMLHttpRequest (); xhr.open (" GET "," http: // Example ". Com / servlet? Key = "+ encodeurcomponent (key)); Xhr.send (null);"Post", "http://example.com/servlet"); Xhr.send ("key =" + encodeurIC component (key)); -
Use to send a crossbrowser compatible Ajax request (above
xhrcode works in real browsers only, for MSIE compatibility, you "(" http: //example.com/servlet " , {"Key": key});Note that jQuery's already transparent request parameters automatically encode all the way, so come Should not be "
encodeurIComponent ().
Any method, key just request.getParameter ( "Key") will be available in servlet by .
Comments
Post a Comment