Search code examples
jspjakarta-eeservletsscriptletinbox

Submitting variable from jsp to servlet on page load


I am designing an inbox system that takes the user name from the session of a jsp page and sends it to the servlet, this servlet then loads the inbox table(from the database) based on the username and returns it to the same jsp page.

I can put a submit button to send the user name to the servlet by clicking it, but how do i pass it automatically from the jsp page to the servlet without creating a form and submit button.


Solution

  • that is where you need the ajax.

    change your submit button into a html button and the onclick function, do a ajax call to your servlet and do the stuff there, and pass the output to the jsp through the print stream.

    <input type="button" onClick="loadInbox();" value="inbox"/>
    

    and your loadInbox() function will do the ajax:

    function loadInbox(){
      $.ajax({
                type: "POST",
                data: { "userId": userId },
                url: 'YourServletName',
                dataType: 'json',  
                "success": function (data) {
                    if (data != null) {
                        var vdata = JSON.parse(data);
                        console.log("output from server" + vdata);    
                    },
                "error": function (data) {
                    console.log("error "+ data);
                }
            });     
    
    }
    

    and in your servlet (YourServletName) class, you do your logic stuff and pass the output to print stream:

    void doPost(...... request, ... response){
     PrintWriter out = response.getWriter();
    
     // get the userId from request:
     String userId = request.getParameter("userId");
    
    // do your logic stuff :
    // get the output and print it to output stream:
      String yourOutput = "{ 'output': 'This is an example output'}";
    
      out.print(yourOutput);
      out.flush();
      out.close();
    }
    

    That is all you have to do. and the out.println(yourOutput); will pass the response of your logic/result in to the "success" method of the ajax call if it is ok. check your web console in developer mode to verify the response set from the servlet is what you get as json string/object.

    remember to add jquery library to your javascript libraries!

    hope this will guide you...Happy Ajax !