response对象

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>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、JSP内置对象简介 JSP内置对象是Web容器创建的一组对象,不使用new关键字就可以使用的内置对象。开发者可...
    年少懵懂丶流年梦阅读 3,864评论 0 8
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,080评论 19 139
  • 这部分主要是与Java Web和Web Service相关的面试题。 96、阐述Servlet和CGI的区别? 答...
    杂货铺老板阅读 1,432评论 0 10
  • 本文包括:1、Filter简介2、Filter是如何实现拦截的?3、Filter开发入门4、Filter的生命周期...
    廖少少阅读 7,362评论 3 56
  • 文字 需要朴素 需要高级的朴素 做人也是 应该真诚 应该高级真诚 生活更是 亲昵自然 亲昵高级自然 返朴的就真 真...
    龙青阅读 274评论 0 1