简体   繁体   中英

send java class instance from javascript (via ajax) to jsp or servlet

I am trying to send the JAVA CLASS INSTANCE from my javascript code to the JSP file via ajax . How can i send ? I tried sending the instance like this :

   data = {}
   data['my_instance'] = JAVA_CLASS_INSTANCE

and sending this data via ajax , problem is , in JSP, it is receiving it as a string rather than a class

By the way, I am getting the java class instance like this :

<script type='text/javascript'>
     var class_instance = "<%= my_class_instance %>"; //if this method is wrong, plz tell me correct method to get instance and send via ajax. Already I have a form, along with the form data, i am trying to send this class also. If there is anyother good way for this, just tell me. 
</script>

(Updated below)

Fundamentally, what you send from the client to the server via ajax is always a string. It can only be turned into something else by a server-side process interpreting it.

The question doesn't seem to make any sense. Unless you're using a Java applet on the client and LiveConnect , you don't have a Java class instance on the client at all.

If you did have a Java class instance on the client (eg, from the applet), the only way to send it to the server would be:

  1. Serialize it to a byte stream.

  2. Encode that byte stream into a string (Base64 or similar).

  3. Send that encoded string to the server via ajax.

  4. Decode the string back into a byte stream on the server.

  5. Deserialize it on the server.

...and there would almost certainly be a much better way of getting that information from the client to the server.


You've edited your question to say:

By the way, I am getting the java class instance like this :

 <script type='text/javascript'> \n     var class_instance = "<%= my_class_instance %>"; \n</script>  

That won't give you a "Java class instance" on the browser. At best, you'll have a string with some information in it. More likely, depending on what's inside your my_class_instance server-side variable, you'll have a JavaScript syntax error. (Eg, if you have a ' or a line break or an invalid JavaScript escape sequence, etc., inside it.)

If you believe that's a Java class instance, you need to step back and study the fundamentals of web applications before trying to write this code.

You are writing scriptlet to your jsp. This is a bad thing 99.9% of times. You should avoid it all the times. Most of the case, you can write it better with the jstl .

And more importantly, your code is not going to put the java object instance to client browser. It's totally wrong.

Please take a look. How to avoid using scriptlets in my JSP page?

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