简体   繁体   中英

servlet's response to a jsp page

Lets say a servlet text.java returns an html content to a jsp page index.jsp.

IN index.jsp

<button onclick="location.href='text'">CLICK</button>

IN text.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
     out.println("<b>HELLO</b>");
    } finally { 
        out.close();
    }
} 

Now we say that servlet responds to the web browser's request, then after clicking on the button why in the url instead of the jsp page the name of the servlet is there and the control is not returned to the jsp page.

Is that only possible with ajax (formelement.innerHTML= ob.responseText()) ? //where var ob = new XMLHttpRequest();

you can proceed like this...

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    String str = "<b>heloo</b>";
    request.setAttribute("result", str);
    request.getRequestDispatcher("/index.jsp").forward(request, response);
}

and in jsp just get the result by :

request.getAttribute("result");

A JSP is a servlet written as a template. Servlets are server-side, and typically do not call each other. This is your web page (wether it was generated through a jsp or not) that exposes a link to a URL, not a java file . When the link is clicked, your browser sends a request to your server for the URL of the link. So on your server this URL (which is up to you to define) has to be mapped to a Servlet class that will handle the request and produce a response. This URL-to-servlet mapping being configured in the web.xml file of your WAR.

you should see how to map servlet in web.xml, search for a basic servlet tutorial.

you cannot give a link like text.java and expect it will fire the text.java servlet. you need to map a url to servlet class

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