一、项目准备阶段🍉
1.创建SpringBoot项目🥝
2.引入需要的依赖🥝
<?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.3.12.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>SpringBoot6</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringBoot6</name>
<description>SpringBoot6</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--swagger的依赖引入-->
<dependency>
<groupId>io.github.jianzhichun</groupId>
<artifactId>spring-boot-starter-swagger2</artifactId>
<version>0.0.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
<!--引入mp-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
<!--mp代码生成器的依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.29</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
3.添加配置文件🥝
application.properties
#数据源信息
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#characterEncoding防止添加数据时出现乱码情况
spring.datasource.url=jdbc:mysql://localhost:3306/qy165-2?serverTimezone=Asia/Shanghai&characterEncoding=UTF8
spring.datasource.username=root
spring.datasource.password=123456
#指定mp映射文件路径 classpath编译后的路径
mybatis-plus.mapper-locations=classpath:/mapper/*.xml
#控制台打印sql日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
前端需要的静态配置文件
4.编辑Swagger配置文件🥝
package com.lzq.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration //表示类似与配置文件
public class SwaggerConfig {
@Bean //加在方法上,表示吧方法的返回结果交于spring容器来管理该对象. 里面封装了接口文档的信息,
public Docket docket(){
Docket docket=new Docket(DocumentationType.SWAGGER_2)
.groupName("阿娇")
.apiInfo(getInfo())
.select()
//只为com.lzq.controller包下的类生成接口文档
.apis(RequestHandlerSelectors.basePackage("com.lzq.system.controller"))
.build();
return docket;
}
private ApiInfo getInfo(){
Contact DEFAULT_CONTACT = new Contact("阿娇", "http://www.jd.com", "110@qq.com");
ApiInfo apiInfo= new ApiInfo("员工管理系统API文档", "员工管理系统API文档",
"1.5", "localhost:8081/doc.html", DEFAULT_CONTACT, "AAA志远网络有限公司", "http://www.aaa.com");
return apiInfo;
}
}
5.创建代码生成器🥝
代码生成器使用的前提:
1.配置有mp代码生成器的依赖
2.配置有swagger文件
3.连接了数据库
CodeGenerator
package com.lzq;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class CodeGenerator {
/**
* <p>
* 读取控制台内容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotBlank(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir( "D:\\xxcl\\idea\\SpringBoot6/src/main/java");
gc.setAuthor("lzq");
gc.setOpen(false);
gc.setSwagger2(true); //实体属性 Swagger2 注解
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/qy165-2?characterEncoding=utf8&serverTimezone=Asia/Shanghai");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName("system");
pc.setParent("com.lzq"); //com.aaa.user
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return "D:\\xxcl\\idea\\SpringBoot6" + "/src/main/resources/mapper/"
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
// \--转义字符 (\\window系统的路径 /linux系统中 但是现在可以混用)
});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判断自定义文件夹是否需要创建
checkDir("调用默认方法创建的目录,自定义目录用");
if (fileType == FileType.MAPPER) {
// 已经生成 mapper 文件判断存在,不想重新生成返回 false
return !new File(filePath).exists();
}
// 允许生成模板文件
return true;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
// templateConfig.setMapper("dao");
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel); //user_name===userName
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共父类
// 写于父类中的公共字段
strategy.setInclude("acl_permission","acl_role","acl_role_permission","acl_user","acl_user_role");
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix("acl_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
二、项目实施阶段🍉
1.目录🥝
2.编写前端登录页面🥝
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="/js/vue.js"></script>
<script type="text/javascript" src="/js/index.js"></script>
<script type="text/javascript" src="/js/axios.min.js"></script>
<link rel="stylesheet" type="text/css" href="/css/index.css">
<style>
html, body, #app {
height: 100%;
margin: 0px;
padding: 0px;
}
.login_container {
background-image: url("../../images/bg.jpg");
height: 100%;
}
.login_box {
width: 450px;
height: 300px;
background: #fff;
border-radius: 3px;
position: absolute;
left: 50%;
top: 50%;
box-shadow: 0 0 10px #ddd;
transform: translate(-50%, -50%);
}
.login_box > .avatar_box {
height: 130px;
width: 130px;
border: 1px solid #eee;
border-radius: 50%;
padding: 10px;
box-shadow: 0 0 10px #ddd;
position: absolute;
left: 50%;
transform: translate(-50%, -50%);
background-color: #fff;
}
.login_box > .avatar_box > img {
width: 100%;
height: 100%;
border-radius: 50%;
background-color: #eee;
}
.login_form {
position: absolute;
bottom: 0;
width: 100%;
padding: 0 20px;
box-sizing: border-box;
}
.btns {
display: flex;
justify-content: flex-end;
}
</style>
</head>
<body>
<div id="app">
<div class="login_container">
<!-- 登录盒子 -->
<div class="login_box">
<!-- 头像 -->
<div class="avatar_box">
<img src="/images/logo.jpg" alt="">
</div>
<!-- 登录表单 -->
<el-form :rules="loginRules" :model="loginForm" ref="LoginFormRef2" label-width="0px" class="login_form">
<!-- 用户名 -->
<el-form-item prop="username">
<el-input v-model="loginForm.username" prefix-icon="el-icon-user-solid"></el-input>
</el-form-item>
<!-- 密码 -->
<el-form-item prop="password">
<el-input type="password" v-model="loginForm.password" prefix-icon="el-icon-lock"></el-input>
</el-form-item>
<!-- 按钮 -->
<el-form-item class="btns">
<el-button type="primary" @click="login">登录</el-button>
<el-button type="info" @click="resetLogin">重置</el-button>
</el-form-item>
</el-form>
</div>
</div>
</div>
</body>
<script>
var app = new Vue({
el: "#app",
data: {
loginForm: {},
loginRules: {},
},
methods: {
login() {
axios.post("/login/list", this.loginForm).then(result => {
if (result.data.code == 200) {
this.$message.success(result.data.msg)
window.location.href = "/views/main.html"
}else {
this.$message.error(result.data.msg)
}
})
},
resetLogin() {
},
}
})
</script>
</html>
3.编写前端需要的接口🥝
package com.lzq.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzq.system.entity.User;
import com.lzq.system.service.IUserRoleService;
import com.lzq.system.service.IUserService;
import com.lzq.vo.LoginVo;
import com.lzq.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
@RestController
@RequestMapping("/login")
public class LoginController {
@Autowired
private IUserService userService;
@PostMapping("/list")
public Result findAll(@RequestBody LoginVo loginVo, HttpSession session){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("username",loginVo.getUsername());
wrapper.eq("password",loginVo.getPassword());
User one = userService.getOne(wrapper);
if (one!=null){
session.setAttribute("user",one);
return new Result(200,"登录成功",null);
}
return new Result(500,"登录失败",null);
}
}
4.编写前端跳转主页面🥝
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="/js/vue.js"></script>
<script type="text/javascript" src="/js/index.js"></script>
<script type="text/javascript" src="/js/axios.min.js"></script>
<link type="text/css" rel="stylesheet" href="/css/index.css">
<style>
html, body, #app {
padding: 0px;
margin: 0px;
height: 100%;
}
.home-container {
height: 100%;
}
.el-header {
background-color: palegoldenrod;
display: flex;
justify-content: space-between;
padding-left: 0px;
align-items: center;
color: white;
font-size: 20px;
}
.el-header > div {
display: flex;
align-items: center;
}
.el-header > div > span {
margin-left: 15px;
}
.el-aside {
background-color: #333744;
}
.el-aside > .el-menu {
border-right: none;
font-size: 12px;
}
.el-main {
background-color: #f1f1f1;
}
</style>
</head>
<body>
<div id="app">
<el-container class="home-container">
<el-header>
头部
</el-header>
<el-container>
<el-aside width="200px">
<!-- 侧边栏菜单 -->
<el-menu
background-color="#333744"
:unique-opened="true"
text-color="#fff"
active-text-color="#ffd04b"
router
>
<!-- 一级菜单 index就是跳转路径-->
<el-submenu :index="first.id" v-for="first in leftMenu">
<!-- 一级菜单模板 -->
<template slot="title">
<!-- 文本 -->
<span :class="first.icon" style="font-size: 15px;"> {{first.name}}</span>
</template>
<!-- 二级子菜单 -->
<!-- 二级子菜单 -->
<el-menu-item :index="second.path" v-for="second in first.children">
<!-- 二级菜单模板 -->
<template slot="title">
<!-- 图标 -->
<!-- 文本 -->
<span :class="second.icon" style="font-size: 15px;"
@click="showContent(second.path,second.name)"> {{second.name}}</span>
</template>
</el-menu-item>
</el-submenu>
</el-menu>
</el-aside>
<el-main>
主题
</el-main>
</el-container>
</el-container>
</div>
</body>
<script>
var app = new Vue({
el: "#app",
data: {
leftMenu: [],
},
created() {
this.getMenu()
},
methods: {
getMenu() {
axios.get("/system/permission/left").then(result=>{
if (result.data.code==200){
this.leftMenu=result.data.data;
}
})
},
}
})
</script>
</html>
5.编写跳转主页面侧边栏数据接口🥝
controller层
package com.lzq.system.controller;
import com.lzq.system.entity.Permission;
import com.lzq.system.entity.User;
import com.lzq.system.service.IPermissionService;
import com.lzq.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
import java.util.List;
/**
* <p>
* 权限 前端控制器
* </p>
*
* @author lzq
* @since 2023-06-20
*/
@RestController
@RequestMapping("/system/permission")
public class PermissionController {
@Autowired
private IPermissionService permissionService;
@GetMapping("/left")
public Result findAll(HttpSession session) {
System.out.println("111111111111111");
User user = (User) session.getAttribute("user");
System.out.println(user);
List<Permission> all = permissionService.findAll(user.getId());
System.out.println(all);
if (all != null) {
return new Result(200, "查询菜单成功", all);
} else {
return new Result(500, "查询失败", null);
}
}
}
service层
PermissionServiceImpl
文章来源:https://www.toymoban.com/news/detail-771980.html
package com.lzq.system.service.impl;
import com.lzq.system.entity.Permission;
import com.lzq.system.mapper.PermissionMapper;
import com.lzq.system.service.IPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* <p>
* 权限 服务实现类
* </p>
*
* @author lzq
* @since 2023-06-20
*/
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {
@Autowired
private PermissionMapper permissionMapper;
@Override
public List<Permission> findAll(String id) {
List<Permission> all = permissionMapper.findAll(id);
System.out.println(all);
//查询一级菜单
List<Permission> collect = all.stream().filter(item -> item.getPid().equals("1")).collect(Collectors.toList());
System.out.println(collect+"二级菜单");
//查询一级菜单下的二级菜单
for (Permission f : collect) {
ArrayList<Permission> permissions = new ArrayList<>();
for (Permission t : all) {
if (f.getId().equals(t.getPid())) {
permissions.add(t);
}
}
f.setChildren(permissions);
}
return collect;
}
}
mapper层
PermissionMapper.xml
文章来源地址https://www.toymoban.com/news/detail-771980.html
<?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.lzq.system.mapper.PermissionMapper">
<select id="findAll" resultType="com.lzq.system.entity.Permission">
select p.* from acl_user_role ur join acl_role_permission rp on ur.role_id=rp.role_id
join acl_permission p on rp.permission_id=p.id
where ur.user_id=#{userid} and p.type=1
</select>
</mapper>
到了这里,关于SpringBoot项目登录与主页面(从建项目开始详细教程)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!