简体   繁体   中英

Handling a get request with a response

So as the title suggests, to handle a get request, you create a doGet method and pass in a http servlet request and response.

Now an example code snippet I am looking at below is confusing me. This is:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Yahoo!!!!!!!!</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("My First Servlet");
    out.println("</body>");
    out.println("</html>");

}

The line which confuses me is:

  PrintWriter out = response.getWriter();

Is this assigning the output to the response object? The assignment to me reads: "assign whatever is in response.getWriter to PrintWriter 'out'" and not the other way round, so how on earth is the output being returned as a response? is it being handled automatically beneath the curtains or am I missing something blindly obvious?

Thank you

Adding some information to Response object may not be necessary done with assignment. When you change Response object with some set method - that's the same assignment. Right? So in your example you just writing some information to Response's object Writer parameter with println method which play a role of assignment.

In a servlet the response data can be sent as text or in binary form.

For character data (text) PrintWriter is used whose object can be obtained from getWriter()

For binary data use ServletOutputStream. ServletOutputStream can be obtained from getOutputStream() .

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