(一)请求重定向的概念
1.重定向是指当浏览器向Tomcat服务器发送请求时,由于一个Servlet1类无法完成所有请求响应工作,这时候Servlet1类会通知浏览器重新定向到另一个Servlet2类。浏览器再次发送请求Servlet2,来获得Servlet2的响应。
(二)使用HttpServletResponse对象实现请求重定向
1.代码演示
创建servlet实例
package com.haha;
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;
@WebServlet("/LoginDemo")
public class LoginDemo extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
String username=request.getParameter("username");
String password=request.getParameter("password");
if(("123").equals(username)&&("123").equals(password)){
response.sendRedirect("/ServletDemo/Welcome.html");
}else{
response.sendRedirect("/ServletDemo/login.html");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
配置Servlet对象
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>ServletDemo</display-name>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.haha.LoginDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/wwwppp</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
创建登录界面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
<form action="/ServletDemo/LoginDemo" method="get">
用户名:<input type="text" name="username" /><br><br>
密 码:<input type="password" name="password"/><br><br><br>
<input type="submit" value="登录">
<input type="reset" value="重置">
</form>
</center>
</body>
</html>
创建欢迎界面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
欢迎来到魔鬼训练营
</body>
</html>
2.输出结果