How to pass a value of a variable from a java class to the jsp page

后端 未结 3 372
傲寒
傲寒 2020-12-31 19:28

I have 2 files named Admin.java and index.jsp.

In Admin.java through a function I retrieve the value of the varible named

相关标签:
3条回答
  • 2020-12-31 19:33

    If this is an ajax request, you can forward the request into another jsp page rather than return. With this

    getServletContext().getRequestDispatcher("/ajax.jsp").forward(request, response);
    
    create the jsp page(ajax.jsp) on your webcontent and add this sample code.
    
    <p>${rest}</p> 
    <!-- Note: You can actually design your html here. 
         You can also format this as an xml file and let your js do the work.
    //-->
    

    Another way is replace your System.out.println with this

    PrintWriter out = response.getWriter();
    out.print("The value of res been passed is "+res);
    

    but I guess this is a bad practice. See example here.

    0 讨论(0)
  • 2020-12-31 19:35

    From your code,

    request.setAttribute("rest", res);
    

    You shouldn't set it as request attribute. Setting request attributes is only useful if you're forwarding to a JSP file. You need to write it straight to the response yourself. Replace the line by

    response.getWriter().write(res);
    

    This way it'll end up in the response body and be available as variable response in your JS function.

    See also:

    • How to update current page by Servlet/Ajax?
    0 讨论(0)
  • 2020-12-31 19:55

    Seems like you're doing AJAX, so I'd say your response would need to be encoded in an AJAX-compatible way (JSON, XML, ...).

    If you do AJAX-encoding, your function might look like this:

    function(response)
    {
     var toplevel = response.<your_top_level_element>;
    } 
    

    Edit:

    We're using JSON Simple for JSON encoding.

    Our Java backend then looks like this (simplified version without error checking):

    public String execute()
    {
      JSONObject jsonResult = new JSONObject();
    
      jsonResult.put( "result", "ok");
    
      return jsonResult.toJSONString();
    }
    

    And in the Javascript function:

    function(response)
    {
     var result = response.result; //now yields "ok"
    }
    
    0 讨论(0)
提交回复
热议问题