简体   繁体   English

如何将响应从servlet发送到客户端?

[英]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. 我正在尝试将.xml文件形式的响应从Java servlet发送到客户端。 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). 只需调用servlet的URL,即可将您带到客户端(浏览器)。 You don't need to do anything specific. 您不需要做任何特定的事情。

So, if your servlet is mapped like this, 因此,如果您的servlet是这样映射的,

<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! 只需调用URL http://www.example.com/context/MyServlet在浏览器中获取XML!

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>");
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM