• SpringBoot中使用MySQL存用户信息, 日志的使用


    SpringBoot中使用MySQL存用户信息

    UserController类

    package com.tedu.secboot.controller;
    import com.tarena.mnmp.api.SendParam;
    import com.tedu.secboot.entity.User;
    import com.tedu.secboot.util.DBUtil;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.client.RestTemplate;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.Random;
    
    @Controller
    public class UserController {
        private static Logger logger = LoggerFactory.getLogger(UserController.class);//导入日志
    
        @RequestMapping("/regUser")    
        /*之前写法
        public void reg(HttpServletRequest request, HttpServletResponse response){
            System.out.println("开始处理注册");
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String nickname = request.getParameter("nickname");
            String ageStr = request.getParameter("age");
            int age = Integer.parseInt(ageStr);
            System.out.println(username+","+password+","+nickname+","+age);
        }*/
    
        /**
         * SpringMVC框架会根据先通过User的无参构造器实例化User
         * 并利用User对象的属性名去request中获取同名参数并利用User对象上对应属性的set方法将值设置到该属性上。
         *
         * 因此如果以自己定义的一个对象作为参数时,该对象的类要满足:
         * 1:属性名与浏览器传递过来的参数名一致
         * 2:类要有无参公开的构造器
         * 3:属性有set方法
         * 注:只要类设计符合JAVA_BEAN设计规范就可以。
         */
    //    public void reg(User user,HttpServletResponse response){
    //        System.out.println(user);
    //    }
    
        //方法上的参数名要与原request.getParameter()方法传入的字符串内容一致(相当于与表单输入框名字一致)
        public void reg(String username,String password,String nickname,int age,String phone, HttpServletResponse response){
          //日志
            logger.debug("开始处理注册");//debug级别一般记录的是用于跟踪程序执行流程
            logger.info(username+","+password+","+nickname+","+age+","+phone);//info通常记录程序所用到的数据,当我们获取用户信息时可通过info记录
            //必要验证工作
            if(username==null||username.isEmpty()||password==null||password.isEmpty()||
                    nickname==null||nickname.isEmpty()||phone==null||phone.isEmpty()||
                    !phone.matches("[0-9]{11}")){
                //warn用于记录警告内容。例如:正常注册前端验证后通常不会进到这个if里,进来这里说明用户绕过了前端验证,这里要警告程序员。
                logger.warn("注册信息验证错误:"+username+","+password+","+nickname+","+age+","+phone);
                //要求浏览器查看错误提示页面
                try {
                    response.sendRedirect("/reg_info_error.html");
                } catch (IOException e) {
                    e.printStackTrace();
                    //error用于记录程序实际出现的错误。
                    logger.error(e.getMessage(),e);
                }
                return;
            }
            //2
            /*
                将该注册用户插入到数据库userinfo表中。
                插入成功后,响应注册成功页面
             */
            try (
                    Connection conn = DBUtil.getConnection();
            ){
                String sql1 = "SELECT username FROM userinfo WHERE username=?";
                PreparedStatement ps = conn.prepareStatement(sql1);
                ps.setString(1,username);
                ResultSet rs = ps.executeQuery();
                if(rs.next()){//结果集若存在记录,该用户已存在。
                    response.sendRedirect("/have_user.html");
                    return;
                }
    
                String sql2 = "INSERT INTO userinfo(username,password,nickname,age) " +
                        "VALUES (?,?,?,?)";
                ps = conn.prepareStatement(sql2);
                ps.setString(1,username);
                ps.setString(2,password);
                ps.setString(3,nickname);
                ps.setInt(4,age);
                int sum = ps.executeUpdate();
                if(sum>0){
                    response.sendRedirect("/reg_success.html");
                    //发送短信
                    String code = randomCode();//生成验证码
                    System.out.println("验证码:"+code);
                    //创建发送参数对象
                    SendParam param = new SendParam.DefaultSendParam().defaultSendParam(code,phone);
                    //借助Spring提供的RestTemplate
                    new RestTemplate().postForObject(
                            "http://124.71.224.210:8082/send/sms",
                            param,
                            String.class
                    );//向消息中台发送一个HTTP请求
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        private String randomCode(){
            Random random = new Random();
            StringBuilder builder = new StringBuilder(random.nextInt(1000000)+"");
            for(int i=builder.length();i<6;i++){//随机生成的验证码不足6位时前面补充若干个0达到6位
                builder.insert(0,"0");
            }
            return builder.toString();
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126

    User

    package com.tedu.secboot.entity;
    
    /**
     * 该类的每一个实例用于表示一个注册用户信息
     */
    public class User {
        private int id;
        private String username;
        private String password;
        private String nickname;
        private int age;
    
        public User(){}
    
        public User(int id, String username, String password, String nickname, int age) {
            this.id = id;
            this.username = username;
            this.password = password;
            this.nickname = nickname;
            this.age = age;
        }
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public String getNickname() {
            return nickname;
        }
    
        public void setNickname(String nickname) {
            this.nickname = nickname;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", username='" + username + '\'' +
                    ", password='" + password + '\'' +
                    ", nickname='" + nickname + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73

    日志的使用

    Logger记录日志时常用的方法:

    • trace(): trace级别日志
      所有方法都会被记录到日志中
    • debug():debug级别日志
      debug级别一般记录的是用于跟踪程序执行流程
    • info():info级别日志
      info通常记录程序所用到的数据,当我们获取用户信息时可通过info记录
    • warn():warn级别日志
      warn用于记录警告内容。例如:正常注册前端验证后通常不会进到这个if里,进来这里说明用户绕过了前端验证,这里要警告程序员。
    • error():error级别日志
      error用于记录程序实际出现的错误。

    日志级别:

     trace<debug<info<warn<error
    
    • 1

    例如:

    • 如果在application.properties下指定的日志级别为:trace
      那么上述所有方法都会被记录到日志中。

    • 如果在application.properties下指定的日志级别为:debug
      那么除了trace记录的不会保留,剩下的都会保留

    具体实现

    在这里插入图片描述
    在这里插入图片描述

    更多可以参考这篇文章: 跳转链接

  • 相关阅读:
    洛谷 P1776:宝物筛选 ← 多重背包问题 二进制优化
    工业蒸汽量预测(速通一)
    天宇优配|多家房企发布再融资预案,最牛地产股九连板
    悄然兴起的“跑腿”,正在成为一个千亿市场
    吃货告诉你,PAAS、IAAS和SAAS之间的区别
    消息队列(中间件)
    (面试题) 面试官:如何在forEach的循环里使用break
    使用java连接Libvirtd
    上位机通过Modbus转Profinet网关与CGV300变频器通讯配置案例
    第12集丨唯一的成圣之道
  • 原文地址:https://blog.csdn.net/aiheshuicxy/article/details/128159456