

<%@ 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") ;//页面跳转:重定向, 导致数据丢失
//页面跳转:请求转发, 可以获取到数据,并且 地址栏 没有改变(仍然保留 转发时的页面check.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"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
登录成功!<br/>
欢迎您:
<%
String name = request.getParameter("uname") ;
out.print(name) ;
%>
</body>
</html>重定向结果:

请求转发结果:

请求转发 | 重定向 | |
|---|---|---|
地址栏是否改变 | 不变(check.jsp) | 改变(success.jsp) |
是否保留第一次请求时的数据 | 保留 | 不保留 |
请求的次数 | 1 | 2 |
跳转发生的位置 | 服务端 | 客户端发出的第二次跳转 |
2、
Cookie: name=value
javax.servlet.http.Cookie
public Cookie(String name,String value)
String getName():获取name
String getValue():获取value
void setMaxAge(int expiry);最大有效期 (秒)cookie案例 在webcontext下创建cookie文件夹
response_addCookie.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>
<%
//服务端
Cookie cookie1 = new Cookie("name","zs");
Cookie cookie2 = new Cookie("pwd","abc");
response.addCookie(cookie1);
response.addCookie(cookie2);
//页面跳转到客户端(转发或重定向跳过去)
response.sendRedirect("result.jsp");
%>
</body>
</html>result.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>
<%
//客户端
Cookie[] cookies = request.getCookies();
for(Cookie cookie:cookies){
out.print(cookie.getName()+"--"+cookie.getValue()+"<br/>");
}
%>
</body>
</html>访问:http://localhost:8080/01_jsp/cookie/responseaddCookie.jsp 跳转到 http://localhost:8080/01_jsp/cookie/result.jsp

通过F12可以发现 除了自己设置的Cookie对象外,还有一个name为 JSESSIONID的cookie JSESSIONID为cookie默认自带的



Remote Address: [::1]:8080 相当于 127.0.0.1:8080 Status Code:状态码,以3开头的一般为重定向 重定向、超链接、地址栏直接访问为get方式请求