Java Web-Servlet (one) httpservletresponse detailed (redirect)

Source: Internet
Author: User
Tags throw exception

When the Web server receives an HTTP request from the client (under the premise that the program inherits HttpServlet), the container calls the servlet's doget () or Dopost () method. An instance of the HttpServletRequest interface and an instance of an HttpServletResponse interface are created for each request, encapsulated into parameters passed to the doget () or Dopost () method.
Request and response represent the client's requests to the Web server and the server's response to the client, respectively.

The inheritance structure of HttpServlet is as follows:


Common methods of Servletresponse:
Getoutputstream (): Returns a Servletoutputstream object that is used to send a response to the client (in binary form)
Methods for loopback character data
Servletoutputstream SOS = Response.getoutputstream ();
Sos.write ("Hello,focus". GetBytes ());
Public Servletoutputstream Getoutputstream ()
Throws Java.io.IOException

Getwriter (): Returns the PrintWriter object that sends the character text to the client.
Public Java.io.PrintWriter getwriter ()
Throws Java.io.IOException

To set how the response is encoded to the client
such as: response.setcharacterencoding ("Utf-8");
public void setcharacterencoding (java.lang.String charset)

Set the type when responding to the client
such as: Response.setcontenttype ("text/html");
public void setContentType (java.lang.String type)

Methods of HttpServletResponse:


(1) Simulate the use of Getoutputstream and getwriter two methods to output characters to the browser.
Create a servlet (Demo3.java)
The code is as follows:
Import Java.io.FileInputStream;
Import java.io.IOException;
Import Java.io.PrintWriter;

Import javax.servlet.ServletException;
Import Javax.servlet.ServletOutputStream;
Import Javax.servlet.annotation.WebServlet;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

public class Demo3 extends HttpServlet {
protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
Response.setcontenttype ("Text/html;charset=utf-8");
PrintWriter out = Response.getwriter ();
Out.println ("Hello Focus");
When executed to Sos.write ("Hello Focus"), wrap the Hello focus character back to the Web server
The contents of the response are disassembled and returned to the browser,
Check that the stream also has no output content, if not, detect if the stream is closed, if not,
The stream is closed.
Servletoutputstream SOS = Response.getoutputstream ();
Sos.write ("Hello focus_18". getBytes ());

}

}

Throw exception:
Java.lang.IllegalStateException:getWriter () have already been called for this response
This response Getwriter () method is already in the process of being accessed.

Summarize:
The 1.getOutputStream and Getwriter methods are used to obtain the output binary data, output text data servletoutputstream, PrintWriter object.
2. The two methods of Getoutputstream or getwriter are mutually exclusive in the same response object, and no other method can be called after any of the methods are called.
Data written to the Servletoutputsream or Pintwrite object by a 3.Servlet program is fetched from the servlet engine (Web server) from response, which is used by the servlet engine as the body of the response message. It is then combined with the response status line and each response header to output to the client.
After the 4.Servlet service method finishes, the Servlet engine checks to see if the output stream object returned by the Getwriter or Getoutputstream method has already used the close () method, and if not, the servlet engine calls close ( ) method to close the output stream object.

(2) Flexible use of redirects
In the request processing method of the Servlet class, the parameter data submitted by the client can be obtained, and the logical code can be written to process the request data and finally respond to the client.
Sometimes the servlet class cannot handle your request or cannot handle the request independently and requires additional servlet classes for secondary processing, which requires "redirect" or "Request dispatch".
redirect
The Sendredirect () method provided by the HttpServletRequest interface is used to generate a 302 response and a location response header, which informs the client to revisit the URL specified in the location response header, as follows:
public void Sendredirect (java.lang.String location)
Throws Java.io.IOException
Where the location parameter specifies the URL of the redirect, it can use the absolute URL and the relative Url,servlet container will automatically convert the relative URL to an absolute URL after the Location header field is generated.
Sendredirect () can redirect not only resources to local containers, but also to network sites.

Example:
The Demo3.java code is as follows:

Import Java.io.FileInputStream;
Import java.io.IOException;
Import Java.io.PrintWriter;

Import javax.servlet.ServletException;
Import Javax.servlet.ServletOutputStream;
Import Javax.servlet.annotation.WebServlet;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

public class Demo3 extends HttpServlet {
protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
Response.sendredirect ("/demo/demo4");//A resource that is reset to the specified road strength
}

}
The Demo4.java code is as follows:

Import java.io.IOException;
Import Java.io.PrintWriter;

Import javax.servlet.ServletException;
Import Javax.servlet.annotation.WebServlet;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

public class Demo4 extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    response.setContentType("text/html;charset=utf-8");    PrintWriter out = response.getWriter();    request.setCharacterEncoding("utf-8");    out.println("用户名为:");    out.println(request.getParameter("name"));}

}
When you enter in the browse:
Http://localhost:8080/demo/demo3?name=focus
The display results are as follows:

When the server calls the corresponding method of the Demo4 instance to handle Demo3 this method, the HttpServletRequest instance no longer contains the parameters in the first request, and the request and response are completely new, so the value of the parameter name is NULL.
In this way, the value of name can be obtained.
Response.sendredirect ("/demo/demo4?name=focus");

When username is the value submitted by the user, it can be set.
String username = request.getparameter ("username");
Response.sendredirect ("/demo/demo4?name=" +username);

Summarize:
Sendredirect ("Url?username=focus");
Advantage: The speed of transmitting information is relatively fast
Disadvantage: It can only transfer strings, not an object
Attention:
(1) What is the URL name and variable between the servlet? No.
(2) If more than two values are passed, they must be separated by the & number:
such as: Sendredirect ("servlet address? parameter name = parameter value & parameter name = argument value ...");

Summarize:
1. Use HttpServletResponse to return the most basic characters and control the display of the browser.
2. Through the HttpServletResponse loopback HTTP header, you can control the browser behavior.
3. Through the functions provided by HttpServletResponse, can complete the corresponding functions (such as downloading files, generate random verification code)

Java Web-Servlet (one) httpservletresponse detailed (redirect)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.