java 如何将响应从 servlet 发送到客户端?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5348899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to send response from servlet to client side?
提问by pritsag
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:
我正在尝试以 .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>");
}
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
提前致谢
回答by adarshr
Just invoking the servlet's URL will get you to the client side (browser). You don't need to do anything specific.
只需调用 servlet 的 URL 即可进入客户端(浏览器)。你不需要做任何特定的事情。
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!
回答by Preetham R U
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>");
}
}