栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

基于Spring Boot + Mybatis-plus + git 开发上传入门登录案例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

基于Spring Boot + Mybatis-plus + git 开发上传入门登录案例

一、工具版本

        编写java代码:IdeaIU-2021.1.3

        管理项目依赖:Maven-3.8.3

        管理项目文件:Git-2.34.1

        关系型数据库:Mysql-8.0.27

二、项目搭建

        1.创建MySQL数据库

CREATE DATAbase game_web;
USE game_web;
CREATE TABLE account(
    id INT PRIMARY KEY AUTO_INCREMENT,
    username VARCHAr(8) NOT NULL,
    password VARCHAr(20) NOT NULL
);
INSERT INTO account values(1,'zhangsan','123456');
SELECt * FROM account;

        2.创建spring boot工程,选择Spring initializr,可连接阿里云spring boot地址,填写工程名字

                选择存放路径,Maven项目,java语句,java版本,打成jar包

        

        3.勾选需要使用的技术,Spring,Mysql,Mybatis Plus

        

        4.编写目录结构,所有使用的类需要放在Spring boot自动生成类Application的同一级目录下

        

        5.隐藏指定文件或文件夹

        

        6.更改配置文件格式

        

        7.添加yml文件为Spring boot配置文件,并解决配置文件中自动提示功能消失

         

        8.新建Gitee仓库,Idea集成Git,选择仓库目录默认是当前项目目录,Commit→Romote

        

        9.Spring boot核心配置文件基础配置

# 应用服务 WEB 访问端口
server:
  port: 80

spring:
  # 应用名称
  application:
    name: gameWeb
  # 配置数据库连接信息
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/game_web?serverTimezone=UTC
      username: root
      password: 123456
三、代码编写

        1.前端页面如果有小伙伴帮忙做就好了,这里编写简单html

    

LOGIN IN

Username:

Password:

   

没有账号?点击注册

    
        Sign up
        
已有帐号? 点击登录
Username:
用户名不太受欢迎
Password:
请输入6~20位密码
RepeatPw:
密码重输错误
Captcha:



        2.编写pojo实体类映射数据库中account表,通过Lombok实现注解开发,引入Lombok坐标


    org.projectlombok
    lombok
    1.18.20
    true
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Account {
    private int id;
    private String username;
    private String password;
}

        3.案例以三层架构进行编写,mapper层使用mybatis-plus继承baseMapper

@Mapper
public interface AccountMapper extends baseMapper {
}

        4.service层先编写接口,实现抽象方法,注入mapper

@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountMapper mapper;

    @Override
    public boolean login(String username, String password) {
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        wrapper.eq("password",password);
        Account account = mapper.selectOne(wrapper);
        return account != null;
    }

    @Override
    public int register(String username, String password, String repeatPw) {
        QueryWrapper wrapper = new QueryWrapper<>();
        username = username.strip();
        wrapper.eq("username",username);
        Account user = mapper.selectOne(wrapper);
        if (user != null || username.length() > 8 || username.length() == 0)
            return 10;
        if (password.length() < 6 || password.length() > 20)
            return 100;
        if (!password.equals(repeatPw))
            return 1000;
        Account account = new Account();
        account.setUsername(username);
        account.setPassword(password);
        return mapper.insert(account);
    }
}

        5.controller层,注入service,以Restful风格编写

@Controller
@RequestMapping("/accounts")
public class AccountController {
    @Autowired
    private AccountService service;

    @PostMapping("/login")
    public String login(String username, String password) {
        boolean flag = service.login(username, password);
        if (flag) {
            return "redirect:../html/display.html";
        } else {
            return "redirect:../html/account/login_err.html";
        }
    }

    @PostMapping("/register")
    public String register(HttpServletRequest request, String username, String password, String repeatPw, String checkCode) {
        HttpSession session = request.getSession();
        String checkCodeGen = (String) session.getAttribute("checkCodeGen");
        if (!checkCodeGen.equalsIgnoreCase(checkCode)){
            return "redirect:../html/account/register_cap_err.html";
        }
        int result = service.register(username, password, repeatPw);
        switch (result) {
            case 1 : return "redirect:../html/account/login_suc.html";
            case 10 : return "redirect:../html/account/register_usr_err.html";
            default : return "redirect:../html/account/register_err.html";
        }
    }

    @RequestMapping("/captcha")
    @ResponseBody
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ServletOutputStream os = response.getOutputStream();
        String checkCode = CheckCodeUtil.outputVerifyImage(100, 50, os, 4);
        HttpSession session = request.getSession();
        session.setAttribute("checkCodeGen",checkCode);
    }
}

        6.生成验证码

public class CheckCodeUtil {

    public static final String VERIFY_CODES = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static Random random = new Random();


    public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException {
        String verifyCode = generateVerifyCode(verifySize);
        outputImage(w, h, os, verifyCode);
        return verifyCode;
    }

    public static String generateVerifyCode(int verifySize) {
        return generateVerifyCode(verifySize, VERIFY_CODES);
    }

    public static String generateVerifyCode(int verifySize, String sources) {
        // 未设定展示源的字码,赋默认值大写字母+数字
        if (sources == null || sources.length() == 0) {
            sources = VERIFY_CODES;
        }
        int codesLen = sources.length();
        Random rand = new Random(System.currentTimeMillis());
        StringBuilder verifyCode = new StringBuilder(verifySize);
        for (int i = 0; i < verifySize; i++) {
            verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
        }
        return verifyCode.toString();
    }

    public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
        String verifyCode = generateVerifyCode(verifySize);
        outputImage(w, h, outputFile, verifyCode);
        return verifyCode;
    }

    public static void outputImage(int w, int h, File outputFile, String code) throws IOException {
        if (outputFile == null) {
            return;
        }
        File dir = outputFile.getParentFile();
        //文件不存在
        if (!dir.exists()) {
            //创建
            dir.mkdirs();
        }
        try {
            outputFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(outputFile);
            outputImage(w, h, fos, code);
            fos.close();
        } catch (IOException e) {
            throw e;
        }
    }

    public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
        int verifySize = code.length();
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Random rand = new Random();
        Graphics2D g2 = image.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 创建颜色集合,使用java.awt包下的类
        Color[] colors = new Color[5];
        Color[] colorSpaces = new Color[]{Color.WHITE, Color.CYAN,
                Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
                Color.PINK, Color.YELLOW};
        float[] fractions = new float[colors.length];
        for (int i = 0; i < colors.length; i++) {
            colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
            fractions[i] = rand.nextFloat();
        }
        Arrays.sort(fractions);
        // 设置边框色
        g2.setColor(Color.GRAY);
        g2.fillRect(0, 0, w, h);

        Color c = getRandColor(200, 250);
        // 设置背景色
        g2.setColor(c);
        g2.fillRect(0, 2, w, h - 4);

        // 绘制干扰线
        Random random = new Random();
        // 设置线条的颜色
        g2.setColor(getRandColor(160, 200));
        for (int i = 0; i < 20; i++) {
            int x = random.nextInt(w - 1);
            int y = random.nextInt(h - 1);
            int xl = random.nextInt(6) + 1;
            int yl = random.nextInt(12) + 1;
            g2.drawLine(x, y, x + xl + 40, y + yl + 20);
        }

        // 添加噪点
        // 噪声率
        float yawpRate = 0.05f;
        int area = (int) (yawpRate * w * h);
        for (int i = 0; i < area; i++) {
            int x = random.nextInt(w);
            int y = random.nextInt(h);
            // 获取随机颜色
            int rgb = getRandomIntColor();
            image.setRGB(x, y, rgb);
        }
        // 添加图片扭曲
        shear(g2, w, h, c);

        g2.setColor(getRandColor(100, 160));
        int fontSize = h - 4;
        Font font = new Font("Algerian", Font.ITALIC, fontSize);
        g2.setFont(font);
        char[] chars = code.toCharArray();
        for (int i = 0; i < verifySize; i++) {
            AffineTransform affine = new AffineTransform();
            affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize / 2, h / 2);
            g2.setTransform(affine);
            g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
        }

        g2.dispose();
        ImageIO.write(image, "jpg", os);
    }

    private static Color getRandColor(int fc, int bc) {
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    private static int getRandomIntColor() {
        int[] rgb = getRandomRgb();
        int color = 0;
        for (int c : rgb) {
            color = color << 8;
            color = color | c;
        }
        return color;
    }

    private static int[] getRandomRgb() {
        int[] rgb = new int[3];
        for (int i = 0; i < 3; i++) {
            rgb[i] = random.nextInt(255);
        }
        return rgb;
    }

    private static void shear(Graphics g, int w1, int h1, Color color) {
        shearX(g, w1, h1, color);
        shearY(g, w1, h1, color);
    }

    private static void shearX(Graphics g, int w1, int h1, Color color) {

        int period = random.nextInt(2);

        boolean borderGap = true;
        int frames = 1;
        int phase = random.nextInt(2);

        for (int i = 0; i < h1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                    + (6.2831853071795862D * (double) phase)
                    / (double) frames);
            g.copyArea(0, i, w1, 1, (int) d, 0);
            if (borderGap) {
                g.setColor(color);
                g.drawLine((int) d, i, 0, i);
                g.drawLine((int) d + w1, i, w1, i);
            }
        }

    }

    private static void shearY(Graphics g, int w1, int h1, Color color) {

        int period = random.nextInt(40) + 10; // 50;

        boolean borderGap = true;
        int frames = 20;
        int phase = 7;
        for (int i = 0; i < w1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                    + (6.2831853071795862D * (double) phase)
                    / (double) frames);
            g.copyArea(i, 0, 1, h1, 0, (int) d);
            if (borderGap) {
                g.setColor(color);
                g.drawLine(i, (int) d, i, 0);
                g.drawLine(i, (int) d + h1, i, h1);
            }

        }

    }
}
四、测试代码

        1.测试mapper层

@RunWith(SpringRunner.class)
@SpringBootTest
public class AccountDaoTest {
    @Autowired
    private AccountMapper mapper;

    @Test
    void textRepeat(){
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("username","b");
        Account account = mapper.selectOne(wrapper);
        System.out.println(account);
    }

    @Test
    void testQuery(){
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("username","zhangsan");
        wrapper.eq("password","123456");
        Account account = mapper.selectOne(wrapper);
        System.out.println(account);
    }

    @Test
    void testInsert(){
        Account account = new Account();
        account.setUsername("wangwu");
        account.setPassword("345678");
        int result = mapper.insert(account);
        System.out.println(result);
        System.out.println(account.getId());
    }

}

        2.测试service层

@RunWith(SpringRunner.class)
@SpringBootTest
public class AccountServiceTest {
    @Autowired
    private AccountService service;

    @Test
    public void login(){
        String username = "zhangsan";
        String password = "123456";
        boolean result = service.login(username, password);
        System.out.println(result?1:0);
    }

    @Test
    public void register(){
        String username = "xiss";
        String password = "345678";
        String repeatPw = "123456";
        int result = service.register(username, password,repeatPw);
        System.out.println(result);
    }
}

        3.测试controller,在任意浏览器中地址访问栏输入localhost/html/account/login.html

由于前端知识匮乏,后端代码通过资源重定向实现页面跳转,而在此次项目编写过程中,前端代码花费了大量的时间,之后可以使用异步通信axios和前端框架vue实现全栈,登录成功后跳转至display.html页面,进行对列表的增删改查,可见https://gitee.com/axiaoze/game-web

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/749560.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号