解析request的请求转发与response的重定向区别

1.response对象方法简介

response:响应对象
提供的方法:
void addCookie(Cookie cookie);服务器向客户端增加cookie对象
void sendRedirect(String location)throws IOException:页面跳转的一种方法重定向方法。
void setContetType(String type):设置服务器端响应的编码(设置服务器端的contentType类型)


2.示例:登录

login.jsp->check.jsp->success.jsp
登录后检查密码是否正确,正确则跳到success.jsp页面

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
        <form action="check.jsp" method = "post">
        用&nbsp;户&nbsp;名:<input type = "text" name = "uname"><br/>
        &nbsp;密&nbsp;&nbsp;码:<input type = "password" name = "pwd"><br/>
        <input type = "reset" value = "重置">
        &nbsp;&nbsp;&nbsp;
        <input type = "submit" value = "登录"><br/>
        </form>
</body>
</html>


check.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
        <%
            request.setCharacterEncoding("UTF-8");
            String name = request.getParameter("uname");
            String password = request.getParameter("pwd");
            if((name.equals("zs")) && (password.equals("12345")))
            {
                response.sendRedirect("success.jsp");
    //            request.getRequestDispatcher("success.jsp").forward(request, response);
            }else
            {
                out.print("用户名或者密码错误");
            }
        %>
</body>
</html>

success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <%
        String name = request.getParameter("uname");
        out.print(name+"欢迎您!");
    %>
</body>
</html>

输入正确的用户名密码跳转到了success.jsp但是用户名没有获取。注意观察地址栏

如果使用request.getRequestDispatcher(“success.jsp”).forward(request, response);
地址栏如下

地址栏不同,而且获取到了用户名的值。


3.区别

重定向:response.sendRedirect(“success.jsp”);
请求转发:request.getRequestDispatcher(“success.jsp”).forward(request, response);
区别在于:
请求转发

重定向



概括:最重要的是理解他们两者的区别:
就是请求转发他只执行一次,他不会跳转到success,在其内部就获得了用户名参数。
重定向执行两次,check验证对了以后需要返回客户端告诉他应该去找success。

可以关注自建Blog:http://47.107.118.184

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值