简体   繁体   中英

How to send response from servlet to client side?

I am trying to send response in form of an .xml file from a Java servlet to the client. For that I have written the code below:

if (result) {
    response.setContentType("text/xml");

    PrintWriter out = response.getWriter();

    out.println("<Login>");
    out.println("<status>"+successStatus+"</status>");
    out.println("<username>"+userDTO.getFirstname()+"</username>");
    out.println("<sessionId>"+hSession.getId()+"</sessionId>");
    out.println("<timestamp>"+hSession.getLastAccessedTime()+"</timestamp>");
    out.println("<timeout>"+hSession.getLastAccessedTime()+"</timeout>");
    out.println("</Login>");
}

How can I check on the client whether I get this response or not? Do I need to send the response explicitly or is the above code sufficient to send the response to the client?

Thanks in advance

Just invoking the servlet's URL will get you to the client side (browser). You don't need to do anything specific.

So, if your servlet is mapped like this,

<servlet>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>com.test.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/MyServlet</url-pattern>
</servlet-mapping>

Just invoking the URL http://www.example.com/context/MyServlet will get you the XML on the browser!

public class HelloWorld extends HttpServlet {

  public void doGet(HttpServletRequest req, HttpServletResponse res)
                               throws ServletException, IOException {

    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    out.println("<HTML>");
    out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>");
    out.println("<BODY>");
    out.println("<BIG>Hello World</BIG>");
    out.println("</BODY></HTML>");
  }
}

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