使用Springboot整合Vue项目案例—登录界面

使用Springboot整合Vue项目案例

  • 登录案例
    • 前端代码
    • 后台接口

登录案例

这是登录效果图

使用Springboot整合Vue项目案例—登录界面_第1张图片

前端代码

  • 前端使用vue+elementui+axios
  • 后端使用springboot+mybatis-plus

使用WebStorm写前端界面
使用Springboot整合Vue项目案例—登录界面_第2张图片
前端项目目录结构
使用Springboot整合Vue项目案例—登录界面_第3张图片
(1)创建一个组件页面login.vue

<template>
    
    <div class="login_container">
        
        <div class="login_box">
            
            <div class="avatar_box">
                <img src="../assets/images/shanzhi.jpg" alt="">
            div>
            
            <el-form class="login_form" :model="loginFormData" :rules="loginFormRules" ref="loginFromRef">
                <el-form-item prop="loginName">
                    <el-input  v-model="loginFormData.loginName" prefix-icon="el-icon-user">el-input>
                el-form-item>
                <el-form-item  prop="password">
                    <el-input type="password" v-model="loginFormData.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="loginRef">重置el-button>
                el-form-item>
            el-form>

        div>
    div>
template>

CSS样式

<style scoped>
    .login_container{
        background-color: #42b983;
        height: 100%;
    }
    .login_box{
        width: 450px;
        height: 300px;
        background: #fff;
        border-radius: 3px;
        /*绝对定位*/
        position: absolute;
        /*左偏移*/
        left: 50%;
        /*上偏移*/
        top: 50%;
        /*减去容器自身的宽高*/
        transform: translate(-50%,-50%);
    }
    .login_box>.avatar_box{
        height: 130px;
        width: 130px;
        border:1px solid #E9EEF3;
        border-radius: 50%;
        padding: 5px;
        /*阴影*/
        box-shadow: 0 0 10px #ddd;
        position: absolute;
        left: 50%;
        transform: translate(-50%,-50%);
        background-color: lightpink;
    }
    .login_box>.avatar_box>img{
        width: 100%;
        height: 100%;
        border-radius: 50%;
        background-color: #eee;
    }
    /*表单设计css样式*/
    .login_form{
        /*绝对定位*/
        position: absolute;
        bottom: 0;
        width: 100%;
        padding: 0 20px;
        box-sizing: border-box;
    }
    .btns{
        /*流式布局*/
        display: flex;
        justify-content: flex-end;
    }
style>

注意:设置完CSS样式后发现.login_container高度无效。 需要在assets下创建一个全局的css样式
使用Springboot整合Vue项目案例—登录界面_第4张图片
添加如下CSS样式

html,body,#app{
    height: 100%;
    margin: 0;
    padding: 0;
    font-size: 12px;
}

再把上面的全局css导入main.js文件中

//导入全局css
import './assets/css/global.css'

使用Springboot整合Vue项目案例—登录界面_第5张图片
Vue代码

<script>
    export default {
        name: "login",
        methods:{
            loginRef(){
            	//重置方法
                this.$refs.loginFromRef.resetFields();
            },
            //登录方法
            Login(){
                var that=this;
                this.$refs.loginFromRef.validate((valid) =>{
                    if(valid){
                        this.$http.post("http://localhost:8088/sys/login",this.loginFormData).then(function (resp) {
                            //console.log(resp);
                            if(resp.data.code===200){
                                that.$message.success(resp.data.msg);
                                that.$router.push("/home")
                            }else {
                                that.$message.error(resp.data.msg);
                            }
                        })
                    }
                })

            }
        },
        data(){
            return{
                loginFormData:{
                    loginName:"",
                    password:""

                },
                loginFormRules:{
                    loginName:[
                        {required:true,message:"账号不能为空",triangle: "blur"},
                        {min:5,max:15,message:"账号的长度必须5~15",triangle: "blur"}
                    ],
                    password:[
                        {required:true,message:"密码不能为空",triangle: "blur"},
                        {min:5,max:15,message:"密码的长度必须5~15",triangle: "blur"}
                    ]
                },
            }
        },

    }
script>

登陆时的表单校验

1.在表单元素上添加 :rules="loginFormRules"
2.在data中定义校验规则: 
     data(){
         return {
             loginFormRules:{
                 
             }
         }
     }
3. 在表单元素上使用指定的校验规则 
     <el-form-item prop="loginName">

使用Springboot整合Vue项目案例—登录界面_第6张图片
重置方法

为表单添加一个属性 ref="名称"

使用Springboot整合Vue项目案例—登录界面_第7张图片

后台接口

后台接口我使用了IDEA写的

(1)创建一个springboot项目

在pom.xml文件中添加依赖

 <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-redisartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
            <version>5.1.47version>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-configuration-processorartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>3.4.1version>
        dependency>
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-generatorartifactId>
            <version>3.4.1version>
        dependency>
        <dependency>
            <groupId>org.apache.velocitygroupId>
            <artifactId>velocity-engine-coreartifactId>
            <version>2.3version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druid-spring-boot-starterartifactId>
            <version>1.2.1version>
        dependency>
        
        <dependency>
            <groupId>com.spring4allgroupId>
            <artifactId>swagger-spring-boot-starterartifactId>
            <version>1.9.1.RELEASEversion>
        dependency>
        <dependency>
            <groupId>com.github.xiaoymingroupId>
            <artifactId>swagger-bootstrap-uiartifactId>
            <version>1.9.6version>
        dependency>
    dependencies>

配置application.properties文件

#数据源
spring.datasource.druid.username=root
spring.datasource.druid.password=123@qwe
spring.datasource.druid.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.druid.url=jdbc:mysql://localhost:3306/vue_login
#端口号 因为8080端口号已经被前端占用所以使用其他端口号
server.port=8088

#日志
logging.level..com.fyx.sys.dao=debug

(2)mybatis-plus的代码生成器

因为登录需要连接数据库,所以我使用了mybatis-plus的代码生成器(根据你自己的包路径、数据库等自行修改内容),代码如下

public class CodeGenerator {
    /**
     * 

* 读取控制台内容 *

*/
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(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/src/main/java"); gc.setAuthor("fyx"); gc.setOpen(false); gc.setServiceName("%sService"); gc.setMapperName("%sDao"); gc.setSwagger2(true); //实体属性 Swagger2 注解 mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/vue_login"); // dsc.setSchemaName("public"); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("123@qwe"); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); pc.setModuleName("sys"); pc.setParent("com.fyx"); pc.setMapper("dao"); mpg.setPackageInfo(pc); // 自定义配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { // to do nothing } }; // 如果模板引擎是 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 projectPath + "/src/main/resources/mapper/" + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // 配置模板 TemplateConfig templateConfig = new TemplateConfig(); templateConfig.setXml(null); mpg.setTemplate(templateConfig); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); //strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!"); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix("acl_");//数据库表名前缀 mpg.setStrategy(strategy); mpg.execute(); } }

(3)swagger的配置

因为我需要用API文档所以加了这个(下面内容根据你自己的自行修改)

@Configuration
public class SwaggerConfig {
    //获取swagger2的实例对象docket
    @Bean
    public Docket getDocket() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .groupName("fyx")
                .apiInfo(apiInfo())
                .select()//设置哪些包下的类生产api接口文档
                .apis(RequestHandlerSelectors.basePackage("com.fyx.sys.controller"))
                //设置哪些请求路径生产接口文档
                .paths(PathSelectors.any())
                .build();
        return docket;
    }

    private ApiInfo apiInfo() {
        Contact DEFAULT_CONTACT = new Contact("是阿星啊", "http://www.bing.com", "[email protected]");
        ApiInfo apiInfo = new ApiInfo("员工管理系统API接口文档", "员工管理系统API接口文档", "1.0", "http://www.bing.com",
                DEFAULT_CONTACT, "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0", new
                ArrayList<VendorExtension>());
        return apiInfo;
    }
}

(4)controller接口

注意:因为项目运行登录时会出现跨域问题,所以要加上@CrossOrigin注解来解决跨域问题

@RestController
@RequestMapping("/sys")
@Api("登陆接口API")
@CrossOrigin//解决跨域问题
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * LoginVo:将登录或注册信息存在这里面,接受登陆者的信息
     * @return
     */
    @PostMapping("/login")
    public Result login(@ApiParam(value ="登录者信息" ) @RequestBody LoginVo loginVo){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",loginVo.getLoginName());
        wrapper.eq("password",loginVo.getPassword());
        User user = userService.getOne(wrapper);
        if(user!=null){
            return new Result(200,"登录成功",user);
        }else {
            return new Result(500,"登录失败",null);
        }
    }
}

创建LoginController之前要创建这两个类

在这里插入图片描述

LoginVo 类(存放登录信息)

@Data
@ApiModel("登陆者对象")
public class LoginVo {

    @ApiModelProperty(value = "账号")
    private String loginName;

    @ApiModelProperty(value = "密码")
    private String password;
}

Result 类(存放接收登录响应信息)

@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel("响应的结果")
public class Result {
    @ApiModelProperty("响应的状态码")
    private Integer code;
    @ApiModelProperty("响应的信息")
    private String msg;
    @ApiModelProperty("响应的数据")
    private Object result;
}

启动类(记得要开启@MapperScan扫描和@EnableSwagger2注解)

使用Springboot整合Vue项目案例—登录界面_第8张图片

启动项目后打开API调用接口前测试一下

使用Springboot整合Vue项目案例—登录界面_第9张图片
测试成功!

回到WebStorm,前端调用后端接口

(1)在main.js中引入axios并挂载到Vue对象中

import axios from 'axios'

//把axios挂载到vue对象
Vue.prototype.$http=axios;

使用Springboot整合Vue项目案例—登录界面_第10张图片

(2)登陆页面ajax请求

          //登录方法
            Login(){
                var that=this;
                this.$refs.loginFromRef.validate((valid) =>{
                    if(valid){
                        this.$http.post("http://localhost:8088/sys/login",this.loginFormData).then(function (resp) {
                            //console.log(resp);
                            if(resp.data.code===200){
                                that.$message.success(resp.data.msg);
                                that.$router.push("/home")
                            }else {
                                that.$message.error(resp.data.msg);
                            }
                        })
                    }
                })
            }

出现跨域问题:就在后端controller中加上@CrossOrigin注解,即可解决跨域问题
在这里插入图片描述
跨域问题

什么情况下会出现跨域问题?
(1)必须是ajax请求
(2)从一个区域请求另一个区时。协议不同或者ip不同或者端口号不同。
跨域到底由谁解决?
前端人员解决或者后端人员解决。

在浏览器输入localhost:8080/#/login 登录测试

登录成功
使用Springboot整合Vue项目案例—登录界面_第11张图片
使用Springboot整合Vue项目案例—登录界面_第12张图片
登录失败
使用Springboot整合Vue项目案例—登录界面_第13张图片

这样,一个简单的springboot整合Vue的登录页面就写好了!

使用Springboot整合Vue项目案例—登录界面_第14张图片

你可能感兴趣的:(Vue,vue)