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;
@Controller
@RequestMapping("customer")
public class CustomerController {
@Autowired
private 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;
@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;
}
@Override
public 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;
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;
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;
@Service
public class CustomerServiceImpl implements ICustomerService {
@Autowired
private CustomerMapper customerMapper;
@Override
public 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;
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;
}
public static boolean checkToken(String token){
return false;
}
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);
}
public static ServerResult updateSuccess(Object data){
return new ServerResult(200,"处理成功",data);
}
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;
}
@Override
public 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 {
@Override
protected 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
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
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;
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: /app
port: 8080
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/dict?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username: root
password: 123456
mvc:
view:
prefix: /
suffix: .jsp
hiddenmethod:
filter:
enabled: true
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/>
</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>
<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>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
<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>