正文

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

文章摘要

这篇文章主要介绍如何在JSP页面中使用Cookie和Session来实现用户登录和注册的功能。通过JavaServer Pages (JSP)技术和JavaScript,文章详细描述了从HTTP请求中获取用户名和密码,并通过Cookie保存用户信息的过程。具体来说,文章讲解了如何根据不同的保存时间(如一天、一周或 forever)设置Cookie的生命周期,以及如何在用户名不存在的情况下读取已存在的Cookie并将其值赋给变量。此外,文章还提到了如何判断用户名是否存在,并根据情况输出相应的提示信息。整体内容围绕如何实现用户登录和注册功能,并通过Cookie实现信息的持久化和客户端的重定向机制。

 %@ 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>