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

使用Springboot整合Vue项目案例

登录案例

这是登录效果图

在这里插入图片描述

前端代码

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

使用WebStorm写前端界面
在这里插入图片描述
前端项目目录结构
在这里插入图片描述
(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样式
在这里插入图片描述
添加如下CSS样式

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

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

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

在这里插入图片描述
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">

在这里插入图片描述
重置方法

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

在这里插入图片描述

后台接口

后台接口我使用了IDEA写的

(1)创建一个springboot项目

在pom.xml文件中添加依赖

 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </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>
        <!--mp相关的依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.3</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.1</version>
        </dependency>
        <!--swagger2的相关依赖-->
        <dependency>
            <groupId>com.spring4all</groupId>
            <artifactId>swagger-spring-boot-starter</artifactId>
            <version>1.9.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.6</version>
        </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 {
    /**
     * <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();
        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", "1430930278@qq.com");
        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注解)

在这里插入图片描述

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

在这里插入图片描述
测试成功!

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

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

import axios from 'axios'

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

在这里插入图片描述

(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的登录页面就写好了!

在这里插入图片描述

  • 21
    点赞
  • 84
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值