今天抽空写了一个登录的demo项目,使用HBuilderX和IntelliJ IDEA创建前后端分离的项目,并实现简单的登录功能(简单连接数据库判断),通过Ajax与后端的SpringBoot项目进行交互。
目录
第一步:创建前端项目
第二步:准备数据库
第三步、创建后端项目
1、创建springboot项目
2、修改pom.xml
3、修改application.yml
第四步、创建项目使用的包和类
1、数据库实体类
2、数据传输对象
3、控制器层
4、业务层
6、持久层
7、自定义全局异常
8、统一异常处理类
9、web响应实体类
第五步、配置mapper包扫描路径
第六步:测试效果
第一步:创建前端项目
1、打开HBuilderX,点击左上角菜单栏:文件->新建->项目->基本html项目,项目取名为login
2、下载jquery.min.js,将其放在项目的js目录下
3、在项目根目录下创建一个html目录,在html目录下新建登录页面login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>登录页面</title>
<script src="../js/jquery.min.js" charset="utf-8"></script>
<script src="../js/login.js" charset="utf-8"></script>
</head>
<body>
<table>
<tr>
<td>用户名:</td>
<td><input id = "usernamne" /></td>
</tr>
<tr>
<td>密 码:</td>
<td><input id = "password" /></td>
</tr>
<tr>
<td><button type="button" id="login">登录</button></td>
<td><input type="reset" value="重置" /></td>
</tr>
</table>
</body>
</html>
4、在项目根目录下创建一个js目录,在html目录下新建登录页面login.js
let indexPage = "../index.html";
$(function() {
$("#login").click(function() {
// 获取用户输入
let usernamne = $("#usernamne").val();
let password = $("#password").val();
// 使用jquery的ajax提交数据
$.post("http://localhost:8080/user/login", {
username: usernamne,
password: password
}, function(response) {
if(response.code === 200) {
location.href = indexPage;
} else {
alert(response.message);
}
}, "json");
});
});
5、在项目根目录下创建index.html,登录成功会跳转到这个页面,同时显示当前登录的用户名。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>系统首页</title>
<script src="js/jquery.min.js" charset="utf-8"></script>
</head>
<body>
<h1>欢迎登录!<span id="username"></span></h1>
<script>
$(function() {
$.get("http://localhost:8080/user/getLoginUsername", {}, function(response) {
if(response.code === 200) {
$("#username").html(response.data);
} else {
alert(response.message);
}
}, "json");
});
</script>
</body>
</html>
至此,前端项目搭建完成,项目的结构图如下:
第二步:准备数据库
在这里推荐使用Navicat,Navicat使用快速入门
1、新建数据库login
2、在login数据库下创建user表
create table user (
id int primary key auto_increment,
username varchar(255) not null,
password varchar(255) not null
);
insert into user values(1, 'admin', '12345');
第三步、创建后端项目
1、创建springboot项目
在IntelliJ IDEA中创建springboot项目,项目名为login:点击左上角的菜单栏:File -> New -> Project -> Spring Initializer。
在Name后面的输入框中填写项目名login,Java后面的下拉框选择jdk版本为8,点击Next继续下一步,然后点击Finish,至此,springboot项目创建完成。
2、修改pom.xml
修改pom.xml,引入项目使用到的依赖jar包
<?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.5.9</version>
<relativePath />
</parent>
<groupId>com.example</groupId>
<artifactId>login</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
<mysql.version>8.0.28</mysql.version>
<druid.version>1.1.21</druid.version>
<lombok.version>1.18.22</lombok.version>
<mybatis-boot.version>2.2.2</mybatis-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--validation-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
<version>${lombok.version}</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<version>${mysql.version}</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis-boot.version}</version>
</dependency>
<!--druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3、修改application.yml
server:
port: 8083
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/login
type: com.alibaba.druid.pool.DruidDataSource
mybatis-plus:
mapper-locations: classpath:mapper/*Mapper.xml
logging:
level:
com.example.login: debug
第四步、创建项目使用的包和类
1、数据库实体类
项目根目录下新建entity包,在entity包下创建一个实体类User
User.java
package com.example.login.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
@Data
@TableName("user")
public class User implements Serializable {
private static final long serialVersionUID = 18L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
}
2、数据传输对象
项目根目录下新建dto包,在dto包下创建UserLoginDTO
UserLoginDTO.java
package com.example.login.dto;
import lombok.Data;
import javax.validation.constraints.NotEmpty;
@Data
public class UserLoginDTO {
/**
* 用户名
*/
@NotEmpty(message = "用户名不能为空")
private String username;
/**
* 密码
*/
@NotEmpty(message = "密码不能为空")
private String password;
}
3、控制器层
项目根目录下新建controller包,在controller包下创建控制器类UserController
UserController.java
package com.example.login.controller;
import com.example.login.dto.UserLoginDTO;
import com.example.login.restful.JsonResult;
import com.example.login.restful.ResponseCode;
import com.example.login.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@CrossOrigin
@RestController
@RequestMapping(value = "/user", produces = "application/json;charset=utf-8")
public class UserController {
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
/**
* 用户登录
* @param userLoginDTO 用户登录信息
* @return JsonResult
*/
@ApiOperation("用户登录")
@RequestMapping(value = "/login", method = RequestMethod.POST)
public JsonResult<Void> login(@Validated UserLoginDTO userLoginDTO) {
boolean result = userService.login(userLoginDTO);
if (result) {
return JsonResult.success();
} else {
return JsonResult.error(ResponseCode.BAD_REQUEST, "用户名或密码错误~");
}
}
}
4、业务层
①项目根目录下新建service包,在service包下创建UserService接口
UserService.java
package com.example.login.service;
import com.example.login.dto.UserLoginDTO;
public interface UserService {
/**
* 用户登录
* @param userLoginDTO 用户登录信息
* @return boolean
*/
boolean login(UserLoginDTO userLoginDTO);
}
②在service包下新建impl子包,在service.impl包下创建UserService的实现类
UserServiceImpl.java
package com.example.login.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.login.dto.UserLoginDTO;
import com.example.login.entity.User;
import com.example.login.exception.GlobalException;
import com.example.login.mapper.UserMapper;
import com.example.login.restful.ResponseCode;
import com.example.login.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
private final UserMapper userMapper;
@Autowired
public UserServiceImpl(UserMapper mapper) {
this.userMapper = mapper;
}
@Override
public boolean login(UserLoginDTO userLoginDTO) {
String username = userLoginDTO.getUsername();
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("username", username);
User user = userMapper.selectOne(wrapper);
if (user == null) {
throw new GlobalException(ResponseCode.NOT_FOUND, "登录失败,用户名不存在!");
}
return user.getPassword().equals(userLoginDTO.getPassword());
}
}
6、持久层
项目根目录下新建mapper包,在mapper包下创建UserMapper接口
UserMapper.java
package com.example.login.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.login.entity.User;
import org.springframework.stereotype.Repository;
@Repository
public interface UserMapper extends BaseMapper<User> {
}
在resources目录下创建mapper包,创建mybatis的映射文件Mapper.xml(可选)
UserMapper.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.login.mapper.UserMapper">
</mapper>
7、自定义全局异常
在com.example.login包下新建exception包,创建自定义全局异常类GlobalException
package com.example.login.exception;
import com.example.login.restful.ResponseCode;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 自定义全局异常
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class GlobalException extends RuntimeException {
private ResponseCode responseCode;
public GlobalException(ResponseCode responseCode, String message) {
super(message);
setResponseCode(responseCode);
}
}
8、统一异常处理类
在exception包下新建handler包,创建统一异常处理类GlobalExceptionHandler
package com.example.login.exception.handler;
import com.example.login.exception.GlobalException;
import com.example.login.restful.JsonResult;
import com.example.login.restful.ResponseCode;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 处理Exception
* @param exception Exception
* @return JsonResult<Void>
*/
@ExceptionHandler(Exception.class)
public JsonResult<Void> handleException(Exception exception) {
exception.printStackTrace();
return JsonResult.error(ResponseCode.ERROR, exception);
}
/**
* 处理GlobalException
* @param exception GlobalException
* @return JsonResult<Void>
*/
@ExceptionHandler(GlobalException.class)
public JsonResult<Void> handleGlobalException(GlobalException exception) {
exception.printStackTrace();
return JsonResult.error(exception.getResponseCode(), exception);
}
/**
* 处理BindException
* @param exception BindException
* @return JsonResult<Void>
*/
@ExceptionHandler(BindException.class)
public JsonResult<Void> handleBindException(BindException exception) {
exception.printStackTrace();
BindingResult bindingResult = exception.getBindingResult();
FieldError fieldError = bindingResult.getFieldError();
assert fieldError != null;
String defaultMessage = fieldError.getDefaultMessage();
return JsonResult.error(ResponseCode.BAD_REQUEST, defaultMessage);
}
}
9、web响应实体类
新建restful包,创建JsonResult和ResponseCode
JsonResult.java
package com.example.login.restful;
import lombok.Data;
@Data
public class JsonResult<T> {
/**
* 响应状态码
*/
private Integer code;
/**
* 响应提示信息
*/
private String message;
/**
* 响应数据
*/
private T data;
public static JsonResult<Void> success() {
return success(null);
}
public static JsonResult<Void> success(String message) {
return success(message, null);
}
public static <T> JsonResult<T> success(String message, T data) {
JsonResult<T> jsonResult = new JsonResult<>();
jsonResult.setCode(ResponseCode.SUCCESS.getValue());
jsonResult.setMessage(message);
jsonResult.setData(data);
return jsonResult;
}
public static JsonResult<Void> error(ResponseCode responseCode, Throwable e) {
return error(responseCode, e.getMessage());
}
public static JsonResult<Void> error(ResponseCode responseCode, String message) {
JsonResult<Void> jsonResult = new JsonResult<>();
jsonResult.setCode(responseCode.getValue());
jsonResult.setMessage(message);
return jsonResult;
}
}
ResponseCode.java
package com.example.login.restful;
/**
* 响应状态码
*/
public enum ResponseCode {
SUCCESS(200),
BAD_REQUEST(400),
NOT_FOUND(404),
ERROR(500);
private final Integer value;
ResponseCode(Integer value) {
this.value = value;
}
public Integer getValue() {
return value;
}
}
第五步、配置mapper包扫描路径
在Springboot启动类或者任意一个配置类上添加@MapperScan注解,指定mybatis的mapper包扫描路径。
@MapperScan(basePackages = {"com.example.login.mapper"})
package com.example.login;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan(basePackages = "com.example.login.mapper")
@SpringBootApplication
public class LoginApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
第六步:测试效果
1、在idea中启动后端springboot项目
2、在HbuilderX中使用浏览器打开login.html
在页面输入用户名admin、密码12345,点击登录
登录成功,跳转到了登录页面
好了,文章就分享到这里了,最新代码已经上传到代码仓库,可按需获取~
前端项目https://gitcode.net/heyl163_/login.git文章来源:https://www.toymoban.com/news/detail-486855.html
java + springboot实现简单登录认证功能https://gitee.com/he-yunlin/login.git文章来源地址https://www.toymoban.com/news/detail-486855.html
到了这里,关于HBuilderX和IntelliJ IDEA实现简单登录认证功能的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!