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

news/2024/9/19 20:05:16 标签: servlet, 前端, 服务器

前言

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.niftyadmin.cn/n/5664382.html

相关文章

一文搞懂 Flink ExecutionGraph 构建过程源码

一文搞懂 Flink ExecutionGraph 构建过程源码 1 构建起点2 核心方法attachJobGraph()3 构建ExecutionJobVertex4 IntermediateResult5 ExecutionVertex6 IntermediateResultPartition7 Execution8 连接执行图9 ExecutionEdge 链接: 所有 Flink 重要源码点击我 ExecutionGraph…

自动化流程机器人(RPA)

自动化流程机器人&#xff08;RPA&#xff09;正逐渐成为企业提高效率和降低成本的强有力工具。 一、RPA的概念 自动化流程机器人&#xff08;Robotic Process Automation&#xff0c;简称RPA&#xff09;是一种利用软件机器人&#xff08;Robot&#xff09;模拟和执行复杂任务…

算法训练——day16数组交集(是否去重)

349. 两个数组的交集 给定两个数组 nums1 和 nums2 &#xff0c;返回 它们的 交集。输出结果中的每个元素一定是 唯一 的。我们可以 不考虑输出结果的顺序 示例 1&#xff1a; 输入&#xff1a;nums1 [1,2,2,1], nums2 [2,2] 输出&#xff1a;[2]示例 2&#xff1a; 输入…

Centos 7.9 使用 crontab 实现开机启动

[rootlocalhost ~]# crontab -e [rootlocalhost ~]# reboot # crontab -e reboot /path/to/my/program # reboot 表示重启开机的时候运行一次 reboot /test/hello.sh 参考&#xff1a; Linux crontab 命令 https://www.runoob.com/linux/linux-comm-crontab.html Run prog…

Redis中的setnx的使用场景

Redis中的SETNX命令是一个非常有用的工具&#xff0c;特别是在处理分布式系统和并发控制时。SETNX是“Set if Not Exists”的缩写&#xff0c;用于设置键的值&#xff0c;但仅当键不存在时。以下是SETNX命令的一些主要使用场景&#xff1a; 1. 分布式锁 在分布式环境中&#…

SD-WAN如何保障企业数据安全?

SD-WAN&#xff08;软件定义广域网&#xff09;作为一种现代化网络解决方案&#xff0c;不仅能够优化和管理广域网的连接&#xff0c;还集成了一系列安全功能&#xff0c;帮助企业保护其数据安全。以下将详细介绍SD-WAN如何有效保障企业数据安全的机制。 在采用SD-WAN技术之前&…

Java Web开发中处理Response返回值的技巧与实践

在Java Web开发过程中&#xff0c;处理服务器向客户端发送的响应是至关重要的。无论是构建RESTful API还是传统的Web应用&#xff0c;开发者都需要掌握如何有效地控制HTTP响应。本文将探讨如何使用Java来设置和获取Response对象中的返回值&#xff0c;并介绍一些最佳实践。 一…

SpringBoot @InitBinder注解详解

文章目录 一、简介二、主要用途三、使用方法四、注意事项一、简介 @InitBinder是Spring MVC中的一个注解,用于自定义WebDataBinder,这是一个非常重要的概念,因为它允许你控制和格式化表单数据的方式。WebDataBinder用于将请求参数绑定到JavaBean上。 二、主要用途 格式化日…