response对象的主要作用是对客户端的请求进行回应,
response对象的几个常用方法:
public void add(Cookie cookie); 向客户端增加Cookie;
public void setHeader("String name ","String value"); 设置头信息
public void sendRedirect(String location) throws IOException(); 页面跳转,重定向
1设置头信息:
<%@ page contentType="text/html" pageEncoding="GBK"%>
<%@ taglib prefix="c" uri="http://www.mldn.cn/jstl/core"%>
<html>
<head></head>
<body>
<%! //定义全局变量,注意前面的!号,如果没有!号 ,则定义的是局部变量
int count = 0 ;
%>
<%
response.setHeader("refresh","2");//页面2秒一刷新
%>
<h1>您已经访问了<%=count++%>次!</h1>
</body>
</html>
2页面的跳转:
<%@ page contentType="text/html" pageEncoding="GBK"%>
<html>
<head></head>
<body>
<h1>3秒后跳转到hello.htm页面!如果没有跳转请按<a href="hello.htm">这里</a>!</h1>
<%
response.setHeader("refresh","3;url=hello.htm");//3秒后跳转到hello.htm页面
%>
</body>
</html>
或
<%@ page contentType="text/html" pageEncoding="GBK"%>
<html>
<head></head>
<META HTTP-EQUIV="refresh" CONTENT="3;URL=hello.htm">
<body>
<h1>3秒后跳转到hello.htm页面!如果没有跳转请按<a href="hello.htm">这里</a>!</h1>
</body>
</html>
3.response页面跳转
在response对象中提供了一个叫做sendRedirect()的方法,完成页面的跳转
例子:
<%@ page contentType="text/html" pageEncoding="GBK"%>
<html>
<head></head>
<body>
<%
response.sendRedirect("hello.htm");
%>
</body>
</html>
此时页面已经跳转成功,并且地址栏改变了。这种跳转肯定属于客户端跳转,客户端跳转是无法传递 request属性范围内容的。
问题:那么<jsp:forward>和response.sendRedirect()这两种跳转的区别是什么呢? setHeader也算一种跳转!
===如果是<jsp:forward>跳转的话,有如下特点:
.服务器端跳转,跳转之后地址栏不改变,可以传递request的属性。
.而且是属于无条件的跳转,跳转之前的语句会执行,跳转之后的就不会执行了,如果在jsp中使用jdbc的话,一定要在 跳转之前进行数据库的关闭,否则永远就关闭不了了。
===如果是response.sendRedirect()跳转:
.属于客户端跳转,跳转之后地址栏发生改变,不可以传递request的属性
.是在所有的语句都执行完后,才进行的跳转!
<%@ page contentType="text/html" pageEncoding="GBK"%>
<html>
<head></head>
<body>
<% System.out.println("===========forward跳转之前============") ; %>
<jsp:forward page="hello.htm"/>
<% System.out.println("===========forward跳转之后============") ; %>
</body>
</html
<%@ page contentType="text/html" pageEncoding="GBK"%>
<html>
<head></head>
<body>
<% System.out.println("===========forward跳转之前============") ; %>
<%response.sendRedirect("hello.htm");%>
<% System.out.println("===========forward跳转之后============") ; %>
</body>
</html>
4.操作cookie:
<%@ page contentType="text/html" pageEncoding="GBK"%>
<html>
<head></head>
<body>
<%//本程序表示在客户端上设置两个Cookie对象
Cookie c1 = new Cookie("liuhui1","刘辉1");
Cookie c2 = new Cookie("liuhui2","刘辉2");
response.addCookie(c1);
response.addCookie(c2);
%>
</body>
</html>
本程序表示在客户端上设置两个cookie,既然可以设置了,也可以用request对象来取出(必须用request对象,因为客户端在向服务器端发送请求的时候,会发送一个cookie头信息,所有的请求内容都封装为一个request对象当中);
<%@ page contentType="text/html" pageEncoding="GBK"%>
<html>
<head></head>
<body>
<%
Cookie c[] = request.getCookies();//获取cookie
for(int x=0;x<c.length;x++){
%>
<h1><%=c[x].getName()%>-------><%=c[x].getValue()%></h1>
<%
}
%>
</body>
</html>
由于cookie没有设置保存的时间,所以默认是在一个浏览器上保存的, 如果此浏览器关闭,则Cookie消失,如果想要cookie真正保存在客户端上一段时间,则要用Cookie类提供的的方法:setMaxAge()方法。
response对象主要保存的就是服务器端对客户端的回应。cookie本身是存在安全隐患的,如果要存放客户端信息的时候用cookie就行了。