Web项目实战 | 购物系统v2.0 | 开发记录(二)搭建SpringBoot+SSM框架环境 | 配置Druid+MyBatis | 基于Bootstrap实现登陆页面| 图片验证码接口

Web项目实战 | 购物系统v2.0 | 开发记录(二)搭建SpringBoot+SSM框架环境 | 配置Druid+MyBatis | 基于Bootstrap实现登陆页面| 图片验证码接口,第1张

Web项目实战 | 购物系统v2.0 | 开发记录(二)搭建SpringBoot+SSM框架环境 | 配置Druid+MyBatis | 基于Bootstrap实现登陆页面| 图片验证码接口 历史记录

Web项目实战 | 购物系统v2.0 | 开发记录(一)需求分析 | 技术选型 | 系统设计 | 数据表设计 | SpringBoot、SSM、Thymeleaf、Bootstrap…

Web项目实战 | 购物系统v2.0 | 开发记录(二)

文章目录

历史记录Web项目实战 | 购物系统v2.0 | 开发记录(二)一、运行环境二、环境准备

2.1 使用 IDEA 创建SpringBoot项目2.2 导入所需依赖2.3 配置Druid数据源2.4 编写Java类配置Druid2.5 测试Druid 三、MyBatis 逆向工程

3.1 导入所需依赖3.2 逆向工程配置3.3 运行Maven插件启动逆向工程3.4 问题与优化 四、实现登陆页面

4.1 导入所需依赖4.2 实现代码4.3 判断用户是否存在+获取用户头像4.4 通过类配置web首页4.5 图片验证码接口 Captcha 五、Bug & DeBug六、总结

一、运行环境

windows10IDEA 2021.1 专业版JDK8SpringBoot2Druid 1.2.5Bootstrap 4.6.0MySQL 8Navicat 11 二、环境准备


创建 SpringBoot项目,导入相关的起步依赖、配置Druid数据源,测试数据库连接

2.1 使用 IDEA 创建SpringBoot项目

第一步,新建项目

第二步,选择需要引入的依赖,这里不选全也没事,本质上就是在pom.xml添加相关starter起步依赖,后续还可以添加其他的起步依赖

第三步,了解项目结构

SpringBoot的配置文件都必须命名为application,不过它具有三种不同的格式,有properties、yaml、yml,这里笔者使用yml格式,因为看起来整洁许多,如果同时都有配置的话,是有一个优先级的,在同一级目录下优先级(高 -> 低)为 properties -> yml -> yaml
[相关内容的笔记链接]

2.2 导入所需依赖

除了之前选择的Web、Thymeleafr、Lombok以外,还要确保有mysql、autoconfigure等依赖,具体配置如下:
pom.xml



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.6.3
         
    
    com.uni
    simple-shop-system-v2
    0.0.1-SNAPSHOT
    simple-shop-system-v2
    Demo project for Spring Boot
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            mysql
            mysql-connector-java
            runtime
        
        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.boot
            spring-boot-starter-data-jdbc
        

        
            org.springframework.boot
            spring-boot-autoconfigure
            2.5.6
        

  
        
        
        
            org.webjars
            bootstrap
            4.6.0
        

    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    
                        
                            org.projectlombok
                            lombok
                        
                    
                
            
        
    



2.3 配置Druid数据源

在pom.xml里添加相同依赖:
pom.xml


    mysql
    mysql-connector-java
    runtime


    com.alibaba
    druid-spring-boot-starter
    1.2.5

application.yml

spring:
  datasource:
    username: root
    password: 数据库密码
    url: jdbc:mysql://localhost:3306/simple_shop_system_2?useUnicode=true&characterEncoding=UTF-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
2.4 编写Java类配置Druid

其实在导入Druid起步依赖后,它会有默认的配置注入到Spring容器的,其原理就是通过Java类进行配置,观察jar包里的源码内容:

其源码是通过注解进行配置的,而我们在配置时只需要@Configuration注解表示当前类是一个配置类就行,通过源码可以看到,其作者(来自阿里的大佬)留下了他的QQ号~

在配置Druid时需注意,需要配置哪个对象就使用该对象定义一个方法,同时用@Bean注解标记该方法,这样SpringBoot可以将方法返回的结果注入到Spring容器,即完成配置

DruidConfig.java

package com.uni.config;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DruidConfig {
    //配置Druid监控管理后台的servlet
    //内置Servlet容器时没有web.xml文件,所以使用springboot的注册servlet的方式
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid
        var check_usercode = true
        
        var check_password = true
        
        $("#form-usercode").blur(function (){
            let userCode = $(this).val()
            if (userCode != '') {

                
                $.ajax({
                    url: '/login/' + userCode,
                    type: 'GET',
                    async: false,
                    error: (err) => {
                        alert('AJAX请求失败!')
                        console.log(err.status)
                        console.log(err.responseText)
                    },
                    success: (result) => {
                        if (result == 'true') {
                            check_usercode = true
                            $("#form-usercode").removeClass('is-invalid')
                            $("#form-usercode").addClass('is-valid')
                        } else {
                            check_usercode = false
                            $("#form-usercode").removeClass('is-valid')
                            $("#form-usercode").addClass('is-invalid')
                        }
                    }
                })
            } else {
                check_usercode = false
                $("#form-usercode").removeClass('is-valid')
                $("#form-usercode").addClass('is-invalid')
            }
            
            if(check_usercode){
                $.ajax({
                    url: '/imgSrc/' + userCode,
                    type: 'GET',
                    async: false,
                    dataType: 'text',
                    error: (err) => {
                        alert('查找身份AJAX请求失败!')
                        console.log(err.responseText)
                    },
                    success: (imgSrc) => {
                        $('.card-img-top').attr('src', imgSrc)
                    }
                })
            } else $('.card-img-top').attr('src', '/images/user_common.png')
        });
        $("#btn-login").click({
				//... 待实现
        })
    

Controller层:
UserAction.java

@Autowired
private UserService userService;
@GetMapping("/login/{userCode}")
@ResponseBody
public String checkUserCode(@PathVariable String userCode){
        return userService.checkUserCode(userCode) ? "true" : "false";
}
@GetMapping("/imgSrc")
@ResponseBody
public String defaultImgSrc(){
    return "/images/user_common.png";
}
@GetMapping("/imgSrc/{userCode}")
@ResponseBody
public String selectImgSrc(@PathVariable String userCode){
    String imgSrc = userService.getImgSrc(userCode);
    return imgSrc;
}

Service层

@Autowired
UserMapper userMapper;
@Override
public Boolean checkUserCode(String userCode) {
    UserExample example = new UserExample();
    UserExample.Criteria criteria = example.createCriteria();
    criteria.andUserCodeEqualTo(userCode);
    return userMapper.selectByExample(example).size() == 1;
}

@Override
public String getImgSrc(String userCode) {
    List users = userMapper.selectByExample(new UserExample() {{
        Criteria criteria = createCriteria();
        criteria.andUserCodeEqualTo(userCode);
    }});
    return users != null && users.size() == 1? users.get(0).getUserImgSrc() : null;
}
4.4 通过类配置web首页

通过实现WebMvcConfigurer接口,再通过@Configuration注入到Spring容器这种方式可以得SpringMVC进行配置,比如可以将 "/"的请求转发到地址为"login"的视图,后缀默认为html

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("login");
    }
}
4.5 图片验证码接口 Captcha

作者:Hansin1997

项目地址:https://gitee.com/hansin/captcha(已star)

笔者是根据这位大神提供的开发文档实现的图片验证码,总共有以下四步。

第一步,导入依赖
pom.xml


    cn.dustlight.captcha
    captcha-core
    1.0.1

第二步,在SpringBoot启动类中使用注解@EnableCaptcha对captcha使能

package com.uni;

import cn.dustlight.captcha.annotations.EnableCaptcha;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan(value = "com.uni.dao")
@EnableCaptcha
public class SimpleShopSystemV2Application {

    public static void main(String[] args) {
        SpringApplication.run(SimpleShopSystemV2Application.class, args);
    }
}

第三步,在Controller层编写业务逻辑

package com.uni.controller;

import cn.dustlight.captcha.annotations.Codevalue;
import cn.dustlight.captcha.annotations.SendCode;
import cn.dustlight.captcha.annotations.VerifyCode;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class CodeAction {
    
    @RequestMapping("/captcha")
    @SendCode
    public void captcha(@Codevalue String code) {
        // 在此处进行自定义的业务,验证码的生成、发送与储存已由注解 '@SendCode' 完成。
        return ;
    }

    
    @RequestMapping("/code")
    @VerifyCode
    public String index(@Codevalue String code) {
        // 在此处进行自定义的业务,验证码的验证以及销毁已由注解 '@VerifyCode' 完成。
        return String.format("Hello World! (%s)", code);
    }
}

第四步,在HTML中的图片里指定src到Controller层对应的地址

 
五、Bug & DeBug 

使用MyBatis逆向工程后,User表识别错误,识别到了MySQL自带的User用户表

解决:修改表名,所有表加上前缀uni_,然后重新启动Maven插件,逆向生成DAO层接口和SQL映射文件

MyBatsi逆向工程生成的POJO类属性全是小写的,在配置时需在table标签里添加,用于指定当前表遵循驼峰命名规则

Thymeleaf图片没有正常显示

 

解决:去掉/static

六、总结

今天花时间最多的还是在前端设计上,看来很有必要整一套适合自己的页面设计,不然每次都花时间去调样式,太不合理,通过本次开发,更加熟悉了SpringBoot的注解配置,其作用和XML是类似的,需要配置的时候查资料就行,其次是MyBatis逆向工程真的很方便,今天虽然还没真正实现登陆的需求,但是能感觉到根本不需要写SQL语句,直接用生成的方法来调用Mapper接口,比以前一个一个的去写SQL语句方便多了…

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5719759.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存