response响应对象
提供的方法:
void addCookie(Cookie cookie); 服务器向客户端增加cookie对象
void sendRedirect(String location) throws IOException; 页面跳转的一种方式(重定向)
void setContentType(String type); 设置服务端响应的编码(设置服务端tomcat的类型)
示例:登录界面
login.jsp -> check.jsp -> success.jsp
login.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action= "check.jsp" method="post">
用户名:<input type="text" name="uname"><br/>
密码:<input type="password" name="upwd"><br/>
<input type="submit" value = "登陆"><br/>
</form>
</body>
</html>
check.jsp(重定向跳转):
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
String name = request.getParameter("uname");
String pwd = request.getParameter("upwd");
if(name.equals("zs")&&pwd.equals("abc")){//假设zs 密码abc
response.sendRedirect("success.jsp");
}
else{//登陆失败
out.print("用户名或者密码有误!");
}
%>
</body>
</html>
success.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
登录成功!<br/>
欢迎您:
<%
String name = request.getParameter("uname");
out.print(name);
%>
</body>
</html>
运行如下:
这说明重定向确实是跳转了,但是数据(名字)却丢失了。
我现在将重定向改成请求转发:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
String name = request.getParameter("uname");
String pwd = request.getParameter("upwd");
if(name.equals("zs")&&pwd.equals("abc")){//假设zs 密码abc
//response.sendRedirect("success.jsp"); 页面跳转 重定向 导致数据丢失
//换成页面跳转:请求转发 可以获取到数据,并且地址栏没有改变(仍然保留转发时的界面)
request.getRequestDispatcher("success.jsp").forward(request,response);
}
else{//登陆失败
out.print("用户名或者密码有误!");
}
%>
</body>
</html>
可以看到现在页面是成功了,但是地址栏没有改变。
请求转发和重定向的区别:
请求转发 | 重定向 | |
---|---|---|
地址栏是否改变 | 不变(check.jsp) | 改变(success.jsp) |
是否保留第一次请求时的数据 | 保留 | 不保留 |
请求的次数 | 1 | 2 |
跳转发生的位置 | 服务端 | 客户端发出的第二次跳转 |
转发:
张三(客户端)->[服务窗口A(服务端)->服务窗口B]
重定向:
张三(客户端)->服务窗口A(服务器)->去找B
张三(客户端)->服务窗口B(服务器)