当前位置: 首页 > article >正文

从登录到免登录:JSP与Servlet结合Cookie的基本实现

前言

JSP中应用Cookie解析:

用户登录成功后,将用户信息保存到Cookie中,在页面读取Cookie并显示,不需要再次登录可以直接进入页面

第一步:创建JavaWeb项目,配置pom.xml文件

创建maven项目,项目名为Cookie_Demo

 

 pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.example</groupId>
  <artifactId>Cookie_Demo</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>Cookie_Demo Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
<!--Junit单元测试-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
<!--MySQL连接驱动jar包-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.21</version>
    </dependency>
<!--servlet-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
<!--lombok-->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.24</version>
      <scope>provided</scope>
    </dependency>
<!--servlet表达式-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>huihua_gengzong</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
          <encoding>UTF-8</encoding>
        </configuration>
      </plugin>
<!--打包插件-->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.3.2</version>
      </plugin>
<!--jetty服务器插件-->
      <plugin>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-maven-plugin</artifactId>
        <version>9.3.14.v20161028</version>
      </plugin>
<!--tomcat服务器插件-->
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.1</version>
        <configuration>
          <port>8080</port>
          <path>/my_maven_pro</path>
          <uriEncoding>UTF-8</uriEncoding>
          <server>tomcat7</server>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
  <display-name>Archetype Created Web Application</display-name>
</web-app>

第二步:创建登录页面和登录成功后跳转的页面

创建login.html文件作为登录页面,action的url为servlet类对应的映射地址

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/login" method="post">
    账号: <input type="text" name="username"> <br/>
    密码: <input type="password" name="password"> <br/>
    <input type="submit" value="登录">
</form>
</body>
</html>

main.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%--
  Created by IntelliJ IDEA.
  User: 21038
  Date: 2024/9/14
  Time: 14:03
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
        String username=null;
        Cookie[] cookies = request.getCookies();
    for (int i = 0; i <cookies.length ; i++) {
        Cookie cname = cookies[i];
        if (cname.getName().equals("uname")){
            username=cname.getValue();
        }
    }
%>
<%=username %>,登录成功!

</body>
</html>

使用的是jsp语法,从Cookie中获取设置的用户名,在页面中显示

 第三步:创建Servlet类

LoginServlet

 只演示基本的免登录功能的实现,因此没有与数据库进行连接,这里写死判断条件,即用户为admin,密码为123时判断登陆成功

package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet  extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if ("admin".equals(username)&&"123".equals(password)){
            //创建CooKie
            Cookie cname=new Cookie("uname",username);
            //设置有效期
            cname.setMaxAge(60*60*24*14);
            //写入Cookie
            response.addCookie(cname);
            response.sendRedirect("main.jsp");
        }else {
            response.sendRedirect("login.html");
        }
    }
}

添加Cookie的三个步骤:

  • 创建Cookie
  • 设置Cookie有效期
  • 写入Cookie

第四步:项目演示

启动JavaWeb项目 

在浏览器中测试项目 

 账号或密码不正确,返回到登陆页面

账号密码正确,跳转到登陆成功的页面

 

 测试免登陆

重启项目,后直接打开main.jsp页面,如果是免登录,则直接显示,如果需要登陆,则跳回登陆页面(本项目没有实现登陆拦截,无论是否登陆成功都可以直接访问main.jsp页面,主要观察账户名是否显示,若显示,则表示免登陆,若不显示,则表示没有实现免登陆)

此时可以在浏览器中清理Cookie,然后在查看是否能够免登陆

总结

免登录功能的实现主要借助Cookie在浏览器中缓存用户登陆的信息,这种方式是不安全的,因为用户可以自己清理Cookie数据,因此我们通常使用Cookie保存一些不太需要安全保护的信息。 


http://www.kler.cn/news/309450.html

相关文章:

  • react 组件通讯
  • 面试题篇: 跨域问题如何处理(Java和Nginx处理方式)
  • Linux 使用 tar 命令
  • C++掉血迷宫
  • 在vmvare安装飞牛私有云 fnOS体验教程
  • 自动化测试框架pytest命令参数
  • 如何在@GenericGenerator中显式指定schema
  • 友思特方案 | 搭建红外桥梁:嵌入式视觉接口助力红外热像仪传输
  • SpringBoot入门(黑马)
  • 【数据可视化】Arcgis api 4.x 专题图制作之分级色彩,采用自然间断法(使用simple-statistics JS数学统计库生成自然间断点)
  • 0072__ActiveX插件的使用
  • Linux云计算 |【第二阶段】SHELL-DAY5
  • pdf文件怎么转换成ppt?介绍几种pdf转ppt的方法
  • 传感技术的应用
  • 利用正则表达式匹配格式并且获取替换内容中数据并保留
  • VS+QT--实现二进制和十进制的转换(含分数部分)
  • 去中心化的力量:探索Web3的分布式网络
  • 工商银行银企直联接口清单
  • Java高级Day40-QQ项目全代码
  • 使用SQL数据构建问答系统的完整指南
  • Nginx泛域名 解析的匹配前缀绑定或转发到子目录
  • APP测试基本流程与APP测试要点总结
  • 什么是单元测试?怎么做?
  • C++系列-匿名对象
  • linux网络命令:使用最多最广泛的网络抓包工具tcpdump详细介绍
  • MATLAB入门教程
  • 检查一个复数C的实部a和虚部b是否都是有限数值即a和b都不是无限数值、空值cmath.isfinite(x)
  • MES管理系统在智能制造中的重要应用
  • CMU 10423 Generative AI:lec5(Encoder-only Transformers + 阅读材料Bert, ViT)
  • 如何理解BCEWithLogitsLoss()