文章摘要
这篇文章主要介绍了如何使用Java语言和Spring框架来实现基于Cookie的用户登录功能。文章通过代码示例展示了如何从Cookie中读取用户信息,并根据用户是否存在来判断是否允许访问。具体来说,代码从请求中获取Cookie,遍历所有Cookie,查找用户名字段,并通过Session进行验证。如果用户名存在,则打印欢迎消息;否则,重定向用户至登录页面。文章还提到了这种方法在基于Cookie的登录系统中的适用性。
<%@ page language=”java” contentType=”text/html; charset=UTF-8″
pageEncoding=”UTF-8″%>
<!DOCTYPE html>
<html>
<head>
<meta charset=”ISO-8859-1″>
<title>主不在乎</title>
</head>
<body>
<%
String name=(String)session.getAttribute(“username”);
//获取cookie
Cookie[] cookies=request.getCookies();
//cookie存在
if(cookies !=null && cookies.length > 0){
for(Cookie cookie:cookies){
//获取cookie的名字
String cookieName=cookie.getName();
//判断是否与name相等
if(cookieName.equals(“name”)){
//获取cookie的值
String value=cookie.getValue();
name=value;
}
}
out.println(“welcome again: ” + name+”欢迎登录”);
//*************************
// 另一种写法
String v=null;
for(int i=0;i<cookies.length;i++){
if(cookies[i].getName().equals(“name”)){
v=cookies[i].getValue();
}
}
if(v!=null){
out.println(” Hello World “+v);
}
}
//*************************
else {
response.sendRedirect(“login.jsp”);
}
%>
<a href=”https://www.jb51.net/article/login.jsp” >relogin</a>
</body>
</html>