重定向和请求转发

重定向

1. 地址上显示的是最后的那个资源的路径地址

2. 请求次数最少有两次, 服务器在第一次请求后,会返回302 以及一个地址, 浏览器在根据这个地址,执行第二次访问。

3. 可以跳转到任意路径。 不是自己的工程也可以跳。

4. 效率稍微低一点, 执行两次请求。 

5. 后续的请求,没法使用上一次的request存储的数据,或者 没法使用上一次的request对象,因为这是两次不同的请求。

重定向第一种写法

response.setStatus(302);
response.setHeader("location","loginSuccess.html");

重定向第二种写法

response.sendRedirect("loginSuccess.html");

请求转发

1. 地址上显示的是请求servlet的地址。  返回200 ok

2. 请求次数只有一次, 因为是服务器内部帮客户端执行了后续的工作。 

3. 只能跳转自己项目的资源路径 。  

4. 效率上稍微高一点,因为只执行一次请求。 

5. 可以使用上一次的request对象。 
request.getRequestDispatcher("loginSuccess.html").forward(request, response);

区别:

{{img01.png(uploading...)}}

一个登录的实例

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		response.sendRedirect("loginSuccess.html");
//		response.setStatus(302);
//		response.setHeader("location","loginSuccess.html");
//		request.getRequestDispatcher("loginSuccess.html").forward(request, response);
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		try {
			Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/info","root","w19980315");
			Statement statement = con.createStatement();
			ResultSet re = statement.executeQuery("select * from studscore");
			while(re.next()) {
				if(re.getString(1).equals(username) && re.getString(2).equals(password)) {
					response.sendRedirect("loginSuccess.html");
					System.out.println("登录成功啦...");
					return;
				}
//				else {
//					response.sendRedirect("reginFail.html");
//				}
			}
			response.sendRedirect("loginFail.html");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}   

	}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值