jsp实现用户自动登录功能(jsp如何实现登录功能)干货满满

随心笔谈12个月前发布 admin
97 0


%@ page language=”java” import=”java.util.*” pageEncoding=”UTF-8″%>
<%
String path=request.getContextPath();
String basePath=request.getScheme()+”://”+request.getServerName()+”:”+request.getServerPort()+path+”/”;
%>

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>
<head>
<base href=”https://www.jb51.net/article/<%=basePath%>” rel=”external nofollow” rel=”external nofollow” >

<title>My JSP ‘show.jsp’ starting page</title>

<meta http-equiv=”pragma” content=”no-cache”>
<meta http-equiv=”cache-control” content=”no-cache”>
<meta http-equiv=”expires” content=”0″>
<meta http-equiv=”keywords” content=”keyword1,keyword2,keyword3″>
<meta http-equiv=”description” content=”This is my page”>
<!–
<link rel=”stylesheet” type=”text/css” href=”https://www.jb51.net/article/styles.css” rel=”external nofollow” rel=”external nofollow” >
–>

</head>
<body>
<%
//获取username
String name=request.getParameter(“username”);
//判断用户名是否存在
if(name !=null && !name.trim().equals(“”)){
String[] time=request.getParameterValues(“time”);
//设置session值,便于login页面读取
session.setAttribute(“name”, name);
//设置Cookie
Cookie Cookie=new Cookie(“name”,name);
//根据提交选项设置cookie保存时间
if(time !=null){
for(int i=0;i<time.length;i++){
//不保存Cookie
if(time[i].equals(“notSave”)){
Cookie.setMaxAge(0);
}
//保存一天Cookie
if(time[i].equals(“aDay”)){
Cookie.setMaxAge(60*60*24);
}
//保存一周Cookie
if(time[i].equals(“aWeek”)){
Cookie.setMaxAge(60*60*24*7);
}
//永久保存Cookie,设置为100年
if(time[i].equals(“forever”)){
Cookie.setMaxAge(60*60*24*365*100);
}
}
}

//在客户端保存Cookie
response.addCookie(Cookie);
}
else{%>
<%–用户名不存在则进行判断是否已有cookie –%>
<%
//获取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;
}
}
}
}
if(name !=null && !name.trim().equals(“”)){
out.print(“您好: ” + name+”欢迎登录”);
}
else{//否则重定向到登录界面
out.print(“您还没有注册,2秒后转到注册界面!”);
response.setHeader(“refresh”,”2;url=login.jsp”);
%>
如果没有自动跳转,请点击<a href=”https://www.jb51.net/article/login.jsp” rel=”external nofollow” >此处</a>进行跳转
<%
//response.sendRedirect(“login.jsp”);
}
%>

</body>
</html>

© 版权声明

相关文章