HttpServlet中的請求重定向實現

實現方式

第一種:通過302和Location配合的使用,實現重定向

public class TestClass extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setStatus(302);
		response.setHeader("Location", "https://www.baidu.com");
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

第二種:通過sendRedirect(”URL”)方法

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Insert title here</title>
	</head>
	<body>
		<form action="http://localhost:8080/Demo_04/TestClass" method="get">
			用戶名:<input type="text" name="userName">
			密碼:<input type="password" name = "pw">
			<input type="submit" value="登陸按鈕">
		</form>
	</body>
</html>

跳轉

public class TestClass extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("userName");
		String pw = request.getParameter("pw");
		if(name.equals("123")&& pw.equals("qwe")) {
			response.sendRedirect("https://www.baidu.com");
		}else {
			response.setContentType("text/html;charset=utf-8");
			response.getWriter().print("賬號密碼錯誤");
		}
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

重定向的特點

1,瀏覽器地址欄發生變化
2,發送了兩次請求,且都是由瀏覽器發送的請求

重定向的路徑

由於是瀏覽器發送得到的請求,所以路徑必須要帶上項目名稱

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章