@nalan90
2018-06-29T11:16:18.000000Z
字数 2539
阅读 510
JAVAEE开发
Cookie cookie = new Cookie(String key, Object value);
response.addCookie(cookie);
Cookie[] cookies = request.getCookies();
常用方法
Session与Cookie的区别
示例代码
## login.jsp
<%@ page contentType="text/html;charset=UTF-8" import="java.net.*" language="java" %>
<html>
<head>
<title>登录页面</title>
</head>
<body>
<%
String username = "";
String password = "";
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
for (Cookie c: cookies) {
if (c.getName().equals("username")) {
username = URLDecoder.decode(c.getValue(),"utf-8");
}
if (c.getName().equals("password")) {
password = c.getValue();
}
}
}
%>
<h1>用户登录</h1>
<hr>
<form action="dologin.jsp" name="loginForm" method="post">
用户名: <input type="text" name="username" value="<%=username%>"><br>
密码:<input type="password" name="password" value="<%=password%>"><br>
<input type="checkbox" name="isUseCookie" checked="checked">十天内记住我的登录状态<br>
<input type="submit" value="login">
</form>
</body>
</html>
## dologin.jsp
<%@ page contentType="text/html;charset=UTF-8" import="java.net.*" language="java" %>
<%
request.setCharacterEncoding("utf-8");
%>
<%
String[] isUseCookies = request.getParameterValues("isUseCookie");
if (isUseCookies != null && isUseCookies.length > 0) {
String username = URLEncoder.encode(request.getParameter("username"),"utf-8");
String password = request.getParameter("password");
Cookie nameCookie = new Cookie("username", username);
Cookie passwordCookie = new Cookie("password", password);
nameCookie.setMaxAge(600);
passwordCookie.setMaxAge(600);
response.addCookie(nameCookie);
response.addCookie(passwordCookie);
} else {
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
for (Cookie c: cookies) {
if (c.getName().equals("username") || c.getName().equals("password")) {
c.setMaxAge(0);
response.addCookie(c);
}
}
}
}
%>
<a href="users.jsp">查看用户信息</a>
## users.jsp
<%@ page contentType="text/html;charset=UTF-8" import="java.net.*" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
String username = "";
String password = "";
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
for (Cookie c: cookies) {
if (c.getName().equals("username")) {
username = URLDecoder.decode(c.getValue(),"utf-8");
}
if (c.getName().equals("password")) {
password = c.getValue();
}
}
}
%>
<br>
用户名: <%=username%><br>
密码: <%=password%>
</body>
</html>