1.response对象方法简介
response:响应对象
提供的方法:
void addCookie(Cookie cookie);服务器向客户端增加cookie对象
void sendRedirect(String location)throws IOException:页面跳转的一种方法重定向方法。
void setContetType(String type):设置服务器端响应的编码(设置服务器端的contentType类型)
2.示例:登录
login.jsp->check.jsp->success.jsp
登录后检查密码是否正确,正确则跳到success.jsp页面
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; 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 = "pwd"><br/>
<input type = "reset" value = "重置">
<input type = "submit" value = "登录"><br/>
</form>
</body>
</html>
check.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("uname");
String password = request.getParameter("pwd");
if((name.equals("zs")) && (password.equals("12345")))
{
response.sendRedirect("success.jsp");
// request.getRequestDispatcher("success.jsp").forward(request, response);
}else
{
out.print("用户名或者密码错误");
}
%>
</body>
</html>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String name = request.getParameter("uname");
out.print(name+"欢迎您!");
%>
</body>
</html>
输入正确的用户名密码跳转到了success.jsp但是用户名没有获取。注意观察地址栏
如果使用request.getRequestDispatcher(“success.jsp”).forward(request, response);
地址栏如下
地址栏不同,而且获取到了用户名的值。
3.区别
重定向:response.sendRedirect(“success.jsp”);
请求转发:request.getRequestDispatcher(“success.jsp”).forward(request, response);
区别在于:
请求转发
重定向
概括:最重要的是理解他们两者的区别:
就是请求转发他只执行一次,他不会跳转到success,在其内部就获得了用户名参数。
重定向执行两次,check验证对了以后需要返回客户端告诉他应该去找success。
可以关注自建Blog:http://47.107.118.184