response对象的主要作用是对客户端的请求进行响应,将Web服务器处理后的结果发送给客户端。response对象属于javax.servlet.http.HttpServletResponse接口的示例。
response对象的常用方法
方法 | 描述 |
---|---|
public void addCookie(Cookie cookie) | 向客户端增加Cookie |
public void setHeader(String name, String value) | 设置回应的头信息 |
public void sendRedirect(String location) throws java.io.IOException | 页面跳转 |
1. 设置头信息
定时刷新页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>标题</title>
</head>
<body>
<%!
int count = 0;
%>
<%
response.setHeader("refresh", "1");
%>
<h1>已经访问了<%=count++ %></h1>
</body>
</html>
定时跳转页面,例如:3秒后跳转到百度首页
方式一、
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>标题</title>
</head>
<body>
<%
response.setHeader("refresh", "3;url=http://www.baidu.com");
%>
</body>
</html>
方式二、
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="refresh" content="3;url=http://www.baidu.com">
<title>标题</title>
</head>
<body>
</body>
</html>
2. 页面跳转
response.sendRedirect属于客户端跳转。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>标题</title>
</head>
<body>
<%
response.sendRedirect("http://www.baidu.com");
%>
</body>
</html>
3. 操作Cookie
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>标题</title>
</head>
<body>
<%
Cookie c1 = new Cookie("name", "zhangsan");
Cookie c2 = new Cookie("age", "25");
c1.setMaxAge(10);//设置Cookie保存时间为10秒
response.addCookie(c1);
response.addCookie(c2);
%>
</body>
</html>