示例(用Eclipse Jee)
新建ResponseTest01.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Response内置对象</title>
</head>
<body>
<h1> 欢迎学习response内置对象的动态响应</h1>
<p> 将当前页面保存成word文档吗?
<form action = "" method = post>
<INPUT type = "submit" value = "yes" name = "submit">
</form>
<% String str = request.getParameter("submit");
if (str == null)
{str = "";}
if (str.equals("yes"))
{response.setContentType("application/msword;charset=utf-8");}
%>
</body>
</html>
运行结果
新建ResponseTest02.jsp
做一个用户名的输入窗口,如果在文本框中输入正常的用户名,那么就跳转到一个新的窗口;如果在文本框中没有用户名的输入,就通过response的重定向,还留在当前的输入窗口,要求再重新输入
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Response内置对象</title>
</head>
<body>
<h1> 欢迎学习response内置对象的重定向</h1>
<p> 请输入姓名
<form action = "Response.jsp" method = post>
<input type = "text" name = "name">
<input type = "submit" value = "提交" name = "submit">
</form>
</body>
</html>
再创建一个Response.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Response重定向</title>
</head>
<body>
<%
String name = request.getParameter ("name");
if (name == null || name.length() == 0)
{ response.sendRedirect("ResponseTest02.jsp");}
%>
<h1> 欢迎 <%= name %>来到本页面</h1>
</body>
</html>
运行ResponseTest02.jsp
如果不做输入就提交,看似页面没有改变,其实已经通过response的重定向重新进入输入页面了