Latest web development tutorials

Servlet page redirect

When a document is moved to a new location, we need to send to the client in this new position, we need to use the page redirects. Of course, it may be to load balancing, or just for a simple random, these cases are likely to be used to redirect pages.

Redirects the request to another page The easiest way is to use the response objectsendRedirect () method.Here is the definition of this method: the request is redirected to another page The easiest way is to use the method sendRedirect () response object. The following is the definition of this method:

public void HttpServletResponse.sendRedirect (String location)
throws IOException 

This method, together with the response status code and a new page location is sent back to the browser. You can also put together using setStatus () and setHeader () method to achieve the same effect:

String site = "" ;
response.setHeader("Location", site); 


This example shows how Servlet another location be redirected to the page:

package com.w3big.test;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

 * Servlet implementation class PageRedirect
public class PageRedirect extends HttpServlet{
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
      // 设置响应内容类型

      // 要重定向的新位置
      String site = new String("");

      response.setHeader("Location", site);    

Now let's compile the above Servlet, and create the following entry in the web.xml file:



Now by visiting the URL http: // localhost: 8080 / PageRedirect to call this Servlet. This will take you to a given URL