JavaEE学习15之重定向网页

response对象

重定向是通过使用sendRedirect()方法,将响应发送到另一个指定的位置进行处理。

代码示例

  1. index.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
    String welcome="第一次访问";
    String[] info=new String[]{"","",""};
    Cookie[] cook=request.getCookies();
    if (cook!=null){
        for (int i=0;i<cook.length;i++){
            if (cook[i].getName().endsWith("yangCook")){
                info=cook[i].getValue().split("#");
                welcome=",欢迎回来!";
            }
        }
    }
%>
<%=info[0]+welcome %>
<form action="show.jsp" method="post">
    <br>姓名:<input type="text" name="name" value="<%=info[0]%>"><br>
    出生日期:<input type="text" name="birthday" value="<%=info[1]%>"><br>
    邮箱地址:<input type="text" name="mail" value="<%=info[2]%>"><br>
    <input type="submit" value="提交"><br>
</form>
</body>
</html>

以上代码是JavaEE学习13之response的示例,不一样的是,我在注册后跳转的show.jsp内对获取的name进行判断,如果用户名为tom,则会调用response.sendRedirect(“client.jsp”)方法,跳转到client.jsp页面。
2. show.jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
    String name=new String(request.getParameter("name").getBytes("ISO8859_1"),"UTF-8");
    if (name.equals("tom")){
        response.sendRedirect("client.jsp");
    }
    String birthday = new String(request.getParameter("birthday").getBytes("ISO8859_1"),"UTF-8");
    String mail = new String(request.getParameter("mail").getBytes("ISO8859_1"),"UTF-8");
    Cookie myCook=new Cookie("yangCook",name+"#"+birthday+"#"+mail);  //此处将Cook填写index中cook[]比对的endwith内容的名字,即yangCook
    response.addCookie(myCook);
%>
<ul>
    <li>姓名:<%=name%></li>
    <li>出生日期:<%=birthday%></li>
    <li>邮箱地址:<%=mail%></li>
    <li><a href="index.jsp">返回</a> </li>
</ul>
</body>
</html>

以上代码是JavaEE学习13之response的示例。具体内容解释,请点击超链接自行了解此页面解释。
3. client.jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
这是重定向后的页面
</body>
</html>
  1. 运行结果

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值