day02(后端实习)重定向和请求

1、简述重定向和请求转发的定义
(客户端行为)重定向的定义:
客户浏览器发送http请求----》web服务器接受后发送302状态码响应及对应新的location给客户浏览器–》客户浏览器发现是302响应,则自动再发送一个新的http请求,请求url是新的location地址----》服务器根据此请求寻找资源并发送给客户。在这里location可以重定向到任意URL,既然是浏览器重新发出了请求,则就没有什么request传递的概念了。在客户浏览器路径栏显示的是其重定向的路径,客户可以观察到地址的变化的。重定向行为是浏览器做了至少两次的访问请求的。

(服务器行为)请求转发的定义:
客户浏览器发送http请求----》web服务器接受此请求–》调用内部的一个方法在容器内部完成请求处理和转发动作----》将目标资源发送给客户;在这里,转发的路径必须是同一个web容器下的url,其不能转向到其他的web路径上去,中间传递的是自己的容器内的request。在客户浏览器路径栏显示的仍然是其第一次访问的路径,也就是说客户是感觉不到服务器做了转发的。转发行为是浏览器只做了一次访问请求。

在这里插入图片描述

2、请求抓发和重定义的例子:
前端代码:
login_success.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

	<h1>登录成功33!!!</h1>

</body>
</html>

login.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

	<form action="login">
		账号: <input type="text"  name="username"/><br>
		密码: <input type="text"  name="password"/><br>
		<input type="submit"  value="登录"/><br>
	
	</form>

</body>
</html>

后端代码:

package com.itheima.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class LoginServlet extends HttpServlet {
	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("admin".equals(userName) && "123".equals(password)){
			//response.getWriter().write("登录成功");
			/*
			 * 早期的写法:
			 * response.setStatus(302);
			response.setHeader("Location", "login_success.html");*/
			
			//重定向写法: 重新定位方向  /根目录 ,则需要请求至少两次
			response.sendRedirect("login_success.html");
			
			
			//请求转发的写法:只需要请求一次
//			request.getRequestDispatcher("login_success.html").forward(request, response);
		}else{
			response.getWriter().write("登录失败");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

猜你喜欢

转载自blog.csdn.net/StrongHelper/article/details/85028354