response对象
重定向是通过使用sendRedirect()方法,将响应发送到另一个指定的位置进行处理。
代码示例
- 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>
- 运行结果