<code>response</code>对象的主要作用是用于服务器端给客户端的请求进行回应,将web服务器处理后的结果发给客户端。
response是定义在<code>javax.servlet.http.HttpServletResponse</code>接口的实例,其定义如下:
<code>public interface HttpServletResponseextends ServletResponse</code>
<code>response</code>对象的用法:
1.设置头信
1.1定时刷新
<%@ page contentType="text/html" pageEncoding="GBK"%>
<html>
<head>
<title>Java Web 学习</title>
<head>
<body>
<%!
int content=0;//设置全局变量
%>
<%
response.setHeader("refresh","2");//两秒刷新一次页面
%>
<h2>您已经访问了<%=content++%>次</h2>
</body>
</html>
--
1.2页面跳转
<%@ page contentType="text/html" pageEncoding="GBK"%>
<html>
<head>
<title>Java Web 学习</title>
<head>
<body>
<h2>三秒后跳转到hello.html页面,如果没有跳转请点击<a href="hello.html">此处</a>进行跳转</h2>
<%
response.setHeader("refresh","3;URL=hello.html");//三秒后跳转到hello.html页面
%>
</body>
</html>
2.页面跳转
response对象本身也有页面跳转的方法,该方法是在<code>javax.servlet.http .HttpServletResponse</code>接口中定义的方法,该方法的定义如下:
<code>void sendRedirect(java.lang.String location)
throws java.io.IOException</code>
接下来用一个demo来演示这个方法
<%@ page contentType="text/html" pageEncoding="GBK"%>
<html>
<head>
<title>Java Web 学习</title>
<head>
<body>
<h2>三秒后跳转到hello.html页面,如果没有跳转请点击<a
href="hello.html">此处</a>进行跳转</h2>
<%
//属于客户端跳转,无法传递request的属性范围内容,该跳转是在执行完所有语句后才跳转的
response.sendRedirect("hello.html");//三秒后跳转到
hello.html页面
%>
</body>
<html>
%Z__EOI$FLVB2CTP3NX@X`H.png
、
当然,在jsp的跳转指令<jsp:forward>指令中,同样提供了跳转的功能,他属于服务器端端跳转,可以传递<code>request</code>属性该指令属于无条件跳转,跳转之前的语句会被执行,跳转之后的语句将不会被执行。
<%@ page contentType="text/html" pageEncoding="GBK"%>
<html>
<head>
<title>Java Web 学习</title>
<head>
<body>
<%
System.out.println("跳转之前");
%>
<!--
<jsp:forward> 跳转属于服务器端跳转,客户端地址栏不会发生改变,可以传递request属性
但是,这种跳转方式属于无条件的跳转,语句执行到之后立刻跳转,
跳转之前的语句会被执行,跳转之后的语句将不会被执行
-->
<jsp:forward page="hello.html"/>
<%
System.out.println("跳转之后");
%>
</body>
</html>
3.Cooke操作
网友评论