008 登录(index页面获取token) 同步

2024-04-16 21:04

本文主要是介绍008 登录(index页面获取token) 同步,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

    • CustomerController.java
    • Customer.java
    • CustomerMapper.java
    • ICustomerService.java
    • CustomerServiceImpl.java
    • JwtUtil.java
    • ServerResult.java
    • ServletInitializer.java
    • SpringbootDemoApplication.java
    • customer.sql
    • CustomerMapper.xml
    • application.yaml
    • index.jsp
    • login.jsp
    • pom.xml

CustomerController.java

package com.example.controller;import com.example.entity.Customer;
import com.example.service.ICustomerService;
import com.example.util.ServerResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;/*** <p>*  前端控制器* </p>** @author dd* @since 2024-04-16*/
@Controller
@RequestMapping("customer")
public class CustomerController {@Autowiredprivate ICustomerService customerService;@PostMapping("login")public ModelAndView login(String custName,String custPwd){ServerResult result = customerService.login(custName, custPwd);ModelAndView mav =   new ModelAndView();if(result.getCode() == 200){mav.addObject("result",result);mav.setViewName("index");}else{mav.addObject("result",result);mav.setViewName("login");}return mav;}}

Customer.java

package com.example.entity;import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;/*** <p>* * </p>** @author dd* @since 2024-04-16*/
@TableName("customer")
public class Customer implements Serializable {private static final long serialVersionUID = 1L;@TableId(value = "cust_id", type = IdType.AUTO)private Integer custId;private String custName;private Long custTelno;private String custGender;private LocalDate custBirth;/*** 状态*/private Integer status;/*** 版本号用于做乐观锁*/private Integer version;/*** 数据添加的时间*/private LocalDateTime createTime;/*** 数据修改时间*/private LocalDateTime updateTime;private String custPassword;public Integer getCustId() {return custId;}public void setCustId(Integer custId) {this.custId = custId;}public String getCustName() {return custName;}public void setCustName(String custName) {this.custName = custName;}public Long getCustTelno() {return custTelno;}public void setCustTelno(Long custTelno) {this.custTelno = custTelno;}public String getCustGender() {return custGender;}public void setCustGender(String custGender) {this.custGender = custGender;}public LocalDate getCustBirth() {return custBirth;}public void setCustBirth(LocalDate custBirth) {this.custBirth = custBirth;}public Integer getStatus() {return status;}public void setStatus(Integer status) {this.status = status;}public Integer getVersion() {return version;}public void setVersion(Integer version) {this.version = version;}public LocalDateTime getCreateTime() {return createTime;}public void setCreateTime(LocalDateTime createTime) {this.createTime = createTime;}public LocalDateTime getUpdateTime() {return updateTime;}public void setUpdateTime(LocalDateTime updateTime) {this.updateTime = updateTime;}public String getCustPassword() {return custPassword;}public void setCustPassword(String custPassword) {this.custPassword = custPassword;}@Overridepublic String toString() {return "Customer{" +"custId=" + custId +", custName=" + custName +", custTelno=" + custTelno +", custGender=" + custGender +", custBirth=" + custBirth +", status=" + status +", version=" + version +", createTime=" + createTime +", updateTime=" + updateTime +", custPassword=" + custPassword +"}";}
}

CustomerMapper.java

package com.example.mapper;import com.example.entity.Customer;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;/*** <p>*  Mapper 接口* </p>** @author dd* @since 2024-04-16*/
public interface CustomerMapper extends BaseMapper<Customer> {}

ICustomerService.java

package com.example.service;import com.example.entity.Customer;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.util.ServerResult;/*** <p>*  服务类* </p>** @author dd* @since 2024-04-16*/
public interface ICustomerService  {public ServerResult login(String customerName,String customerPassword);}

CustomerServiceImpl.java


package com.example.service.impl;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.entity.Customer;
import com.example.mapper.CustomerMapper;
import com.example.service.ICustomerService;
import com.example.util.JwtUtil;
import com.example.util.ServerResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;/*** <p>*  服务实现类* </p>** @author dd* @since 2024-04-16*/
@Service
public class CustomerServiceImpl  implements ICustomerService {@Autowiredprivate CustomerMapper customerMapper;@Overridepublic ServerResult login(String customerName,String customerPassword){QueryWrapper<Customer> wrapper = new QueryWrapper<>();wrapper.eq("cust_name",customerName).eq("cust_password",customerPassword);Customer customer = customerMapper.selectOne(wrapper);if(customer != null){String token = JwtUtil.createToken(customer.getCustId(),customer.getCustName());return ServerResult.loginSuccess(token);}return ServerResult.loginFail("用户登录失败");}}

JwtUtil.java


package com.example.util;import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;import java.util.Date;
import java.util.HashMap;
import java.util.Map;public class JwtUtil {private static final String jwtToken = "dahkgag7*$";private static long expireTime = 1000*60*60*24;/*** 创建新token* @param customerId 用户id* @param custmoerName* @return*/public static String createToken(Integer customerId,String custmoerName){Map<String,Object> claims = new HashMap<>();claims.put("customerId",customerId);claims.put("customerName",custmoerName);JwtBuilder jwtBuilder = Jwts.builder().signWith(SignatureAlgorithm.HS256,jwtToken).setClaims(claims).setIssuedAt(new Date()).setExpiration(new Date(System.currentTimeMillis()+expireTime));String token = jwtBuilder.compact();return token;}//验证token是否有效/*** 验证token是否有效* @param token 客户端携带的token* @return 返回是否有效*/public static boolean checkToken(String token){return false;}//解析token/*** 解析token* @param token 客户端携带的token* @return 返回登录用户信息(customerIs)*/public static void parseToken(String token){}}

ServerResult.java


package com.example.util;public class ServerResult {private int code;private String msg;private Object data;public static ServerResult getSuccess(Object data){return new ServerResult(200,"查询成功",data);}public static ServerResult getFail(Object data){return new ServerResult(201,"查询失败",data);}/*** 添加、删除、修改的成功* @param data* @return*/public static ServerResult updateSuccess(Object data){return new ServerResult(200,"处理成功",data);}/*** 添加、删除、修改的失败* @param data* @return*/public static ServerResult updateFail(Object data){return new ServerResult(201,"处理失败",data);}public static ServerResult loginSuccess(Object data){return new ServerResult(200,"登录成功",data);}public static ServerResult loginFail(Object data){return new ServerResult(201,"登失败",data);}public ServerResult() {}public ServerResult(int code, String msg, Object data) {this.code = code;this.msg = msg;this.data = data;}public int getCode() {return code;}public void setCode(int code) {this.code = code;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}public Object getData() {return data;}public void setData(Object data) {this.data = data;}@Overridepublic String toString() {return "ServerResult{" +"code=" + code +", msg='" + msg + '\'' +", data=" + data +'}';}
}

ServletInitializer.java


package com.example;import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;public class ServletInitializer extends SpringBootServletInitializer {@Overrideprotected SpringApplicationBuilder configure(SpringApplicationBuilder application) {return application.sources(SpringbootDemoApplication.class);}}

SpringbootDemoApplication.java


package com.example;import org.apache.ibatis.annotations.Mapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
@MapperScan("com.example.mapper")
public class SpringbootDemoApplication {public static void main(String[] args) {SpringApplication.run(SpringbootDemoApplication.class, args);}}

customer.sql


/*Navicat Premium Data TransferSource Server         : mysql8_3306Source Server Type    : MySQLSource Server Version : 80029Source Host           : localhost:3306Source Schema         : empdbTarget Server Type    : MySQLTarget Server Version : 80029File Encoding         : 65001Date: 11/04/2024 09:38:17
*/SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;-- ----------------------------
-- Table structure for customer
-- ----------------------------
DROP TABLE IF EXISTS `customer`;
CREATE TABLE `customer`  (`cust_id` int(0) NOT NULL AUTO_INCREMENT,`cust_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,`cust_telno` bigint(0) NOT NULL,`cust_gender` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,`cust_birth` date NULL DEFAULT NULL,`status` int(0) NULL DEFAULT NULL COMMENT '状态',`version` int(0) NULL DEFAULT NULL COMMENT '版本号用于做乐观锁',`create_time` datetime(0) NULL DEFAULT NULL COMMENT '数据添加的时间',`update_time` datetime(0) NULL DEFAULT NULL COMMENT '数据修改时间',`cust_password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,PRIMARY KEY (`cust_id`) USING BTREE,UNIQUE INDEX `cust_telno`(`cust_telno`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;-- ----------------------------
-- Records of customer
-- ----------------------------
INSERT INTO `customer` VALUES (1, 'smith', 1849430033, 'M', '2000-01-01', 1, 1, '2023-08-11 13:39:30', NULL, '123456');
INSERT INTO `customer` VALUES (2, 'allen', 13771940583, 'F', '2001-05-01', 1, 1, '2023-07-31 13:40:09', NULL, '123456');SET FOREIGN_KEY_CHECKS = 1;

CustomerMapper.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.CustomerMapper"></mapper>

application.yaml


server:servlet:context-path: /appport: 8080spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/dict?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghaiusername: rootpassword: 123456mvc:view:prefix: / #前缀suffix: .jsp #后缀hiddenmethod:filter:enabled: true # 支持表单 method 转换logging:file:path: d://logger #日志记录level:com.example: debug

index.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body>${result.data}<script>saveToken();function  saveToken(){console.log(typeof "${result.data}")localStorage.setItem("token","${result.data}")}
</script>
</body>
</html>

login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body><form method="post" action="${pageContext.request.contextPath}/customer/login">用户名: <input type="text" name="custName">密码: <input type="password" name="custPwd"><input type="submit" value="登录"></form></body>
</html>

pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.6</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>springboot_demo</artifactId><version>0.0.1-SNAPSHOT</version><packaging>war</packaging><name>springboot_demo</name><description>springboot_demo</description><properties><java.version>1.8</java.version></properties><dependencies><!--====================JWT===============================--><dependency><groupId>commons-codec</groupId><artifactId>commons-codec</artifactId><version>1.9</version></dependency><dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.1</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency><dependency><groupId>taglibs</groupId><artifactId>standard</artifactId><version>1.1.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-tomcat</artifactId><scope>provided</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.28</version></dependency><!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.2</version></dependency><!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-generate --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.5.1</version></dependency><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.31</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

这篇关于008 登录(index页面获取token) 同步的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/909890

相关文章

python获取指定名字的程序的文件路径的两种方法

《python获取指定名字的程序的文件路径的两种方法》本文主要介绍了python获取指定名字的程序的文件路径的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 最近在做项目,需要用到给定一个程序名字就可以自动获取到这个程序在Windows系统下的绝对路径,以下

SpringBoot 获取请求参数的常用注解及用法

《SpringBoot获取请求参数的常用注解及用法》SpringBoot通过@RequestParam、@PathVariable等注解支持从HTTP请求中获取参数,涵盖查询、路径、请求体、头、C... 目录SpringBoot 提供了多种注解来方便地从 HTTP 请求中获取参数以下是主要的注解及其用法:1

JWT + 拦截器实现无状态登录系统

《JWT+拦截器实现无状态登录系统》JWT(JSONWebToken)提供了一种无状态的解决方案:用户登录后,服务器返回一个Token,后续请求携带该Token即可完成身份验证,无需服务器存储会话... 目录✅ 引言 一、JWT 是什么? 二、技术选型 三、项目结构 四、核心代码实现4.1 添加依赖(pom

Python与MySQL实现数据库实时同步的详细步骤

《Python与MySQL实现数据库实时同步的详细步骤》在日常开发中,数据同步是一项常见的需求,本篇文章将使用Python和MySQL来实现数据库实时同步,我们将围绕数据变更捕获、数据处理和数据写入这... 目录前言摘要概述:数据同步方案1. 基本思路2. mysql Binlog 简介实现步骤与代码示例1

C#控制台程序同步调用WebApi实现方式

《C#控制台程序同步调用WebApi实现方式》控制台程序作为Job时,需同步调用WebApi以确保获取返回结果后执行后续操作,否则会引发TaskCanceledException异常,同步处理可避免异... 目录同步调用WebApi方法Cls001类里面的写法总结控制台程序一般当作Job使用,有时候需要控制

Spring Security重写AuthenticationManager实现账号密码登录或者手机号码登录

《SpringSecurity重写AuthenticationManager实现账号密码登录或者手机号码登录》本文主要介绍了SpringSecurity重写AuthenticationManage... 目录一、创建自定义认证提供者CustomAuthenticationProvider二、创建认证业务Us

Springboot项目登录校验功能实现

《Springboot项目登录校验功能实现》本文介绍了Web登录校验的重要性,对比了Cookie、Session和JWT三种会话技术,分析其优缺点,并讲解了过滤器与拦截器的统一拦截方案,推荐使用JWT... 目录引言一、登录校验的基本概念二、HTTP协议的无状态性三、会话跟android踪技术1. Cook

使用Redis快速实现共享Session登录的详细步骤

《使用Redis快速实现共享Session登录的详细步骤》在Web开发中,Session通常用于存储用户的会话信息,允许用户在多个页面之间保持登录状态,Redis是一个开源的高性能键值数据库,广泛用于... 目录前言实现原理:步骤:使用Redis实现共享Session登录1. 引入Redis依赖2. 配置R

Linux线程同步/互斥过程详解

《Linux线程同步/互斥过程详解》文章讲解多线程并发访问导致竞态条件,需通过互斥锁、原子操作和条件变量实现线程安全与同步,分析死锁条件及避免方法,并介绍RAII封装技术提升资源管理效率... 目录01. 资源共享问题1.1 多线程并发访问1.2 临界区与临界资源1.3 锁的引入02. 多线程案例2.1 为

Spring Security 单点登录与自动登录机制的实现原理

《SpringSecurity单点登录与自动登录机制的实现原理》本文探讨SpringSecurity实现单点登录(SSO)与自动登录机制,涵盖JWT跨系统认证、RememberMe持久化Token... 目录一、核心概念解析1.1 单点登录(SSO)1.2 自动登录(Remember Me)二、代码分析三、