HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
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:
/en/en String site = "https://w3resource.net/" ; response.setStatus(response.SC_MOVED_TEMPORARILY); response.setHeader("Location", site); /en/en
This example shows how Servlet another location be redirected to the page:
package com.w3resource.test; import java.io.IOException; 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 */ @WebServlet("/PageRedirect") public class PageRedirect extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置响应内容类型 response.setContentType("text/html;charset=UTF-8"); // 要重定向的新位置 String site = new String("https://w3resource.net/"); response.setStatus(response.SC_MOVED_TEMPORARILY); response.setHeader("Location", site); } }
Now let's compile the above Servlet, and create the following entry in the web.xml file:
/en/en <servlet> <servlet-name>PageRedirect</servlet-name> <servlet-class>PageRedirect</servlet-class> </servlet> <servlet-mapping> <servlet-name>PageRedirect</servlet-name> <url-pattern>/TomcatTest/PageRedirect</url-pattern> </servlet-mapping> /en/en
Now by visiting the URL http: // localhost: 8080 / PageRedirect to call this Servlet. This will take you to a given URL https://w3resource.net.