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

时间:2011-03-18 06:44:46

标签: java servlets

我正在尝试将.xml文件形式的响应从Java servlet发送到客户端。为此我写了下面的代码:

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

如何检查客户端是否收到此回复? 我是否需要明确发送响应,或者上面的代码是否足以将响应发送给客户端?

提前致谢

2 个答案:

答案 0 :(得分:4)

只需调用servlet的URL就可以到达客户端(浏览器)。你不需要做任何具体的事情。

所以,如果你的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>

只需调用URL http://www.example.com/context/MyServlet即可在浏览器中获取XML!

答案 1 :(得分:0)

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