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 MySQL如何通过Binlog获取变更记录恢复数据

《PythonMySQL如何通过Binlog获取变更记录恢复数据》本文介绍了如何使用Python和pymysqlreplication库通过MySQL的二进制日志(Binlog)获取数据库的变更记录... 目录python mysql通过Binlog获取变更记录恢复数据1.安装pymysqlreplicat

C#实现获取电脑中的端口号和硬件信息

《C#实现获取电脑中的端口号和硬件信息》这篇文章主要为大家详细介绍了C#实现获取电脑中的端口号和硬件信息的相关方法,文中的示例代码讲解详细,有需要的小伙伴可以参考一下... 我们经常在使用一个串口软件的时候,发现软件中的端口号并不是普通的COM1,而是带有硬件信息的。那么如果我们使用C#编写软件时候,如

C#实现WinForm控件焦点的获取与失去

《C#实现WinForm控件焦点的获取与失去》在一个数据输入表单中,当用户从一个文本框切换到另一个文本框时,需要准确地判断焦点的转移,以便进行数据验证、提示信息显示等操作,本文将探讨Winform控件... 目录前言获取焦点改变TabIndex属性值调用Focus方法失去焦点总结最后前言在一个数据输入表单

Java后端接口中提取请求头中的Cookie和Token的方法

《Java后端接口中提取请求头中的Cookie和Token的方法》在现代Web开发中,HTTP请求头(Header)是客户端与服务器之间传递信息的重要方式之一,本文将详细介绍如何在Java后端(以Sp... 目录引言1. 背景1.1 什么是 HTTP 请求头?1.2 为什么需要提取请求头?2. 使用 Spr

通过C#获取PDF中指定文本或所有文本的字体信息

《通过C#获取PDF中指定文本或所有文本的字体信息》在设计和出版行业中,字体的选择和使用对最终作品的质量有着重要影响,然而,有时我们可能会遇到包含未知字体的PDF文件,这使得我们无法准确地复制或修改文... 目录引言C# 获取PDF中指定文本的字体信息C# 获取PDF文档中用到的所有字体信息引言在设计和出

python中os.stat().st_size、os.path.getsize()获取文件大小

《python中os.stat().st_size、os.path.getsize()获取文件大小》本文介绍了使用os.stat()和os.path.getsize()函数获取文件大小,文中通过示例代... 目录一、os.stat().st_size二、os.path.getsize()三、函数封装一、os

详谈redis跟数据库的数据同步问题

《详谈redis跟数据库的数据同步问题》文章讨论了在Redis和数据库数据一致性问题上的解决方案,主要比较了先更新Redis缓存再更新数据库和先更新数据库再更新Redis缓存两种方案,文章指出,删除R... 目录一、Redis 数据库数据一致性的解决方案1.1、更新Redis缓存、删除Redis缓存的区别二

python实现自动登录12306自动抢票功能

《python实现自动登录12306自动抢票功能》随着互联网技术的发展,越来越多的人选择通过网络平台购票,特别是在中国,12306作为官方火车票预订平台,承担了巨大的访问量,对于热门线路或者节假日出行... 目录一、遇到的问题?二、改进三、进阶–展望总结一、遇到的问题?1.url-正确的表头:就是首先ur

使用JavaScript将PDF页面中的标注扁平化的操作指南

《使用JavaScript将PDF页面中的标注扁平化的操作指南》扁平化(flatten)操作可以将标注作为矢量图形包含在PDF页面的内容中,使其不可编辑,DynamsoftDocumentViewer... 目录使用Dynamsoft Document Viewer打开一个PDF文件并启用标注添加功能扁平化

SpringBoot项目引入token设置方式

《SpringBoot项目引入token设置方式》本文详细介绍了JWT(JSONWebToken)的基本概念、结构、应用场景以及工作原理,通过动手实践,展示了如何在SpringBoot项目中实现JWT... 目录一. 先了解熟悉JWT(jsON Web Token)1. JSON Web Token是什么鬼