史上最全springboot+vue3+element-plus代码实现web登录页面,包含maven配置

作者 : admin 本文共17165个字,预计阅读时间需要43分钟 发布时间: 2024-06-10 共3人阅读

前端代码

views目录下Login.vue,主要是登录页面的渲染及js信息,具体如下:

<template>
<div>
<div class="login-container">
<div style="width: 350px" class="login-box">
<div style="font-weight: bold;font-size:24px; text-align:center; margin-bottom: 30px ">登 录</div>
<el-form :model="data" ref="ruleFormRef" :rules="rules">
<el-form-item prop="userName">
<el-input  prefix-icon="User" v-model="data.userName" placeholder="请输入账号"/>
</el-form-item>
<el-form-item prop="password">
<el-input  prefix-icon="Lock" v-model="data.password" placeholder="请输入密码"/>
</el-form-item>
<el-form-item>
<el-button type="primary" style="width: 100%" @click="login"> 登 录 </el-button>
</el-form-item>
</el-form>
<div style="margin-top:30px; font-size: 12px ;text-align:right">
还没有账号?请<a href="/registor">注册</a>
</div>
</div>
</div>
</div>
</template>
<script setup >
import {reactive,ref} from "vue"
import loginApi from "@/api/login"
const data = ref({})
const rules = reactive({
userName: [
{ required: true, message: '请输入账号', trigger: 'blur' }
],
password: [
{ required: true, message: '请输入密码', trigger: 'blur' }
]
})
//http://localhost:9090/stu/login
const ruleFormRef=ref({
userName:'',
password:'',
})
const login=()=>{
loginApi(data.value).then(res=>{
if(res.code===200){
console.log('result',"登录成功")
}else{
console.log('result',"登录失败")
}
}).catch(error=>{
console.log(error)
console.log('datassss',data)
})
}
</script>
<style scoped>
.login-container{
min-height: 100vh;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
background-image: url("@/assets/images/login.jpg");
background-size: cover;
}
.login-box{
background-color: rgba(200,200,200,.3);
box-shadow: 0 0 10px rgba(0,0,0,0.1);
padding:35px;
}
</style>

router目录下index.js:

路由处主要配置后端接口的路径:

import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import Registor from '../views/Registor.vue'
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/registor',
name: 'Registor',
component: Registor
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router

api目录下创建config.js、login.js、request.js
其中config.js主要配置请求的ip、端口以及拦截器和响应器,具体代码如下:

import axios from 'axios'
import {ElMessage} from "element-plus";
//创建axios实例
const Service=axios.create({
baseURL:'http://localhost:9090',
headers:{
'Content-Type':'application/json;charset=UTF-8',
'Access-Control-Allow-Origin':'/*'
},
timeout:10000
})
//请求拦截器
Service.interceptors.request.use((config)=>{
return config
}, err => {
console.log(err);
})
//响应拦截器
Service.interceptors.response.use((response)=>{
const res =response.data
if(res.code===200){
return res
}else{
ElMessage.error(res.message || '网络异常')
return res
}
})
export default Service

login.js主要配置登录的接口,相当于封装好,后面可以直接调用,代码如下:

import login from './request'
const loginApi=data=>{
return login.post({
url:"/stu/login",
data
})
}
export default loginApi

request.js主要封装请求,类似于post、get、delete、put等,代码如下:

import Service from "./config"
const get=(config)=>{
return Service({
...config,
method:"get",
params:config.data
})
}
const post=(config)=>{
return Service({
...config,
method:"post",
params:config.data
})
}
export default {
get,
post
}

在vue中还有一些配置类的文件,其中,package.json主要是显示使用的组件信息,如element-plus等,包括版本及组件名称等,通过npm导入或者直接在里面添加都可以,具体代码如下:

{
"name": "vue_demo",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"@element-plus/icons-vue": "^2.3.1",
"axios": "^1.6.7",
"core-js": "^3.8.3",
"element-plus": "^2.5.6",
"vue": "^3.2.13",
"vue-router": "^4.3.0"
},
"devDependencies": {
"@babel/core": "^7.12.16",
"@babel/eslint-parser": "^7.12.16",
"@vue/cli-plugin-babel": "~5.0.0",
"@vue/cli-plugin-eslint": "~5.0.0",
"@vue/cli-service": "~5.0.0",
"eslint": "^7.32.0",
"eslint-plugin-vue": "^8.0.3"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/vue3-essential",
"eslint:recommended"
],
"parserOptions": {
"parser": "@babel/eslint-parser"
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead",
"not ie 11"
]
}

vue.config.js配置一些全局的配置信息,具体代码如下:

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
// 关闭eslint校验
lintOnSave: false
})

后端代码:

controller层,主要写接口,具体代码如下:

package com.example.demo.controller;
import com.alibaba.fastjson.JSON;
import com.example.demo.entity.LoginInfo;
import com.example.demo.entity.Result;
import com.example.demo.entity.StuInfo;
import com.example.demo.service.Login;
import com.example.demo.service.StuManageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@Slf4j
public class WebController {
@Autowired
private StuManageService stuManageService;
@Autowired
private Login login;
@GetMapping("/first")
public String firstRequest(){
return "这是一个测试接口";
}
@PostMapping (value="/stu/login")
public Result login(@RequestBody LoginInfo loginInfo){
log.info("LoginInfo"+JSON.toJSONString(loginInfo));
LoginInfo loginInfo1 = login.getLoginInfo(loginInfo);
Result result=new Result();
result.setCode(200);
result.setMsg("成功");
result.setData(JSON.toJSONString(loginInfo1));
return result;
}
@GetMapping("/getInfo")
public List<StuInfo> getStuInfoList(){
return stuManageService.getStuList();
}
}

service层,主要写业务逻辑,具体代码如下:

package com.example.demo.service;
import com.alibaba.fastjson.JSON;
import com.example.demo.dao.LoginInfoMapper;
import com.example.demo.entity.LoginInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class Login {
@Autowired
private LoginInfoMapper loginInfoMapper;
public LoginInfo getLoginInfo(LoginInfo loginInfo){
log.info("请求参数####"+ JSON.toJSONString(loginInfo));
LoginInfo loginInfo1 = loginInfoMapper.selectLoginInfo(loginInfo);
//没有用户
if(loginInfo1==null){
throw new RuntimeException("账号或用户名密码错误");
}
if(!loginInfo1.getPassword().equals(loginInfo.getPassword())){
throw new RuntimeException("账号或用户名密码错误");
}
return loginInfo1;
}
}
package com.example.demo.service;
import com.example.demo.dao.StuInfoMapper;
import com.example.demo.entity.StuInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class StuManageService {
@Autowired
private StuInfoMapper stuInfoMapper;
public List<StuInfo> getStuList(){
return stuInfoMapper.selectStu();
}
}

dao层,主要是与数据库交互,具体代码和xml如下:

package com.example.demo.dao;
import com.example.demo.entity.LoginInfo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
@Mapper
public interface LoginInfoMapper {
LoginInfo selectLoginInfo(@Param("loginInfo")LoginInfo loginInfo );
}
package com.example.demo.dao;
import com.example.demo.entity.StuInfo;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface StuInfoMapper{
List<StuInfo> selectStu();
}

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.dao.LoginInfoMapper">
<select id="selectLoginInfo" resultType="com.example.demo.entity.LoginInfo">
select * from login where user_name=#{loginInfo.userName}
</select>
</mapper>

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.dao.StuInfoMapper">
<select id="selectStu" resultType="com.example.demo.entity.StuInfo">
select * from stu_info
</select>
<insert id="insertStu" parameterType="com.example.demo.entity.LoginInfo">
insert into stu_info(user_name,password) values(#{userName},#{password})
</insert>
</mapper>

entity层,主要是封装的属性,具体代码如下:

package com.example.demo.entity;
import lombok.Data;
@Data
public class LoginInfo {
private String userName;
private String password;
}
package com.example.demo.entity;
import lombok.Data;
@Data
public class Result {
private Integer code;
private String msg;
private String data;
}
package com.example.demo.entity;
import lombok.Data;
@Data
public class StuInfo {
private Integer id;
private String name;
private String sex;
private Integer age;
}

conf目录主要配置一些全局信息的配置,其中,CorsConfig主要添加一些跨域配置,具体代码如下:

package com.example.demo.conf;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter(){
//创建CORS过滤器对象
CorsConfiguration corsConfiguration = new CorsConfiguration();
//接下去就是设置http头信息
corsConfiguration.addAllowedOrigin("*"); //设置允许跨域请求的域名
corsConfiguration.addAllowedHeader("*"); //设置请求头字段
corsConfiguration.addAllowedMethod("*"); //设置允许的请求方式
// 设置允许跨域的路径
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsFilter(source);
}
}

tomcat的一些配置,具体代码如下:

package com.example.demo.conf;
import org.apache.catalina.connector.Connector;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TomcatConfig {
@Bean
public TomcatServletWebServerFactory webServerFactory() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.addConnectorCustomizers((Connector connector) -> {
connector.setProperty("relaxedPathChars", "\"[\]^`{|}");
connector.setProperty("relaxedQueryChars", "\"[\]^`{|}");
});
return factory;
}
}

后端数据库连接的一些配置,以及mapper读取的一些配置,首先是application.properties,具体如下:

server.port=9090
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/student_manage?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=yuluo15200342100
#配置mapper xml文件的路径
mybatis.type-aliases-package=com.example.demo.entity
mybatis.mapper-locations=classpath:com/example/demo/dao/mapper/*.xml
logging.config: classpath:logback-spring.xml

日志打印设置信息,配置在logback-spring.xml,具体如下:


<configuration>

<include resource="org/springframework/boot/logging/logback/defaults.xml" />
<include resource="org/springframework/boot/logging/logback/console-appender.xml" />

<!---->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!--/home/hfw-client/hfw_log/stdout.log-->
<File>D:/log/hfw-client/hfw_log/stdout.log</File>
<encoder>
<pattern>%date [%level] [%thread] %logger{60} [%file : %line] %msg%n</pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">

<!--/home/hfw-client/hfw_log/stdout.log.%d{yyyy-MM-dd}.log-->
<fileNamePattern>D:/log/hfw-client/hfw_log/stdout.log.%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
</appender>
<logger name="com.example.demo.dao" level="INFO" />
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="FILE"/>
</root>
</configuration>

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 http://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.14</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--Spring boot 核心-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--Mysql依赖包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- druid数据源驱动 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>1.7.2</version>
</dependency>
<!--myabtis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jol</groupId>
<artifactId>jol-core</artifactId>
<version>0.9</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml
false
src/main/resources
**/*.*</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

Maven的setting.xml信息。具体如下:




<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
<!-- localRepository
| The path to the local repository maven will use to store artifacts.
|
| Default: ${user.home}/.m2/repository
/path/to/local/repo
-->
<localRepository>D:\Maven\apache-maven-3.6.3\maven-repository</localRepository>
<!-- interactiveMode
| This will determine whether maven prompts you when it needs input. If set to false,
| maven will use a sensible default value, perhaps based on some other setting, for
| the parameter in question.
|
| Default: true
true
-->
<!-- offline
| Determines whether maven should attempt to connect to the network when executing a build.
| This will have an effect on artifact downloads, artifact deployment, and others.
|
| Default: false
false
-->

<pluginGroups>
<!-- pluginGroup
| Specifies a further group identifier to use for plugin lookup.
com.your.plugins
-->
</pluginGroups>

<proxies>
<!-- proxy
| Specification for one proxy, to be used in connecting to the network.
|
optional
true
http
proxyuser
proxypass
proxy.host.net
80
local.net|some.host.com
-->
</proxies>

<servers>
<!-- server
| Specifies the authentication information to use when connecting to a particular server, identified by
| a unique name within the system (referred to by the 'id' attribute below).
|
| NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are
|       used together.
|
deploymentRepo
repouser
repopwd
-->
<!-- Another sample, using keys to authenticate.
siteServer
/path/to/private/key
optional; leave empty if not used.
-->
</servers>

<mirrors>
<!-- mirror
| Specifies a repository mirror site to use instead of a given repository. The repository that
| this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
| for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
|
mirrorId
repositoryId
Human Readable Name for this Mirror.
http://my.repository.com/repo/path
-->

<mirror>
<id>nexus-aliyun</id>
<mirrorOf>*</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>
</mirrors>

<profiles>
<!-- profile
| Specifies a set of introductions to the build process, to be activated using one or more of the
| mechanisms described above. For inheritance purposes, and to activate profiles via 
| or the command line, profiles have to have an ID that is unique.
|
| An encouraged best practice for profile identification is to use a consistent naming convention
| for profiles, such as 'env-dev', 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc.
| This will make it more intuitive to understand what the set of introduced profiles is attempting
| to accomplish, particularly when you only have a list of profile id's for debug.
|
| This profile example uses the JDK version to trigger activation, and provides a JDK-specific repo.
jdk-1.4
1.4
jdk14
Repository for JDK 1.4 builds
http://www.myhost.com/maven/jdk14
default
always
-->
<!--
| Here is another profile, activated by the system property 'target-env' with a value of 'dev',
| which provides a specific path to the Tomcat instance. To use this, your plugin configuration
| might hypothetically look like:
|
| ...
| 
|   org.myco.myplugins
|   myplugin
|
|   
|     ${tomcatPath}
|   
| 
| ...
|
| NOTE: If you just wanted to inject this configuration whenever someone set 'target-env' to
|       anything, you could just leave off the  inside the activation-property.
|
env-dev
target-env
dev
/path/to/tomcat/instance
-->
 
<profile>
<id>jdk-1.8</id>
<activation>
<activeByDefault>true</activeByDefault>
<jdk>1.8</jdk>
</activation>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
</properties>
</profile>
</profiles>
<!-- activeProfiles
| List of profiles that are active for all builds.
|
alwaysActiveProfile
anotherAlwaysActiveProfile
-->
</settings>
本站无任何商业行为
个人在线分享 » 史上最全springboot+vue3+element-plus代码实现web登录页面,包含maven配置
E-->