1. 程式人生 > >HttpServletResponse物件實現請求重定向(四)

HttpServletResponse物件實現請求重定向(四)

(一)請求重定向的概念

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> 
   密&nbsp;&nbsp;&nbsp;&nbsp;碼:<input  type="password" name="password"/><br><br><br>
   <input type="submit"  value="登入"> 
  &nbsp;&nbsp;&nbsp; <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.輸出結果

這裡寫圖片描述

這裡寫圖片描述