Springboot+uni-app一个简单登录注册功能

springboot初体验

请注意,本文编写于 100 天前,最后修改于 100 天前,其中某些信息可能已经过时。

用到了控制反转[Ico]和依赖注入bean和反射等知识

1.工程目录结构

1.1springboot工程结构

springboot工程结构
springboot工程结构

1.2mysql结构

user.sql

drop database if exists demo;
create database demo;
use demo;
/*用户表*/
create table User(
uid varchar(10) primary key,
uname varchar(20) not null,
password varchar(20) not null,
email varchar(50) unique not null,
sSuper int not null,
delmark int DEFAULT 1

);
ALTER TABLE activity.User ADD UNIQUE (uname);
insert into User values("2017764310","自由","a1138312802","1138312802@qq.com","1","1");
insert into User values("2017764311","哲学家","a1138312802","3481723658@qq.com","1","1");

mysql结构
mysql结构

1.3uni-app效果图

uniapp登录
uniapp登录
uniapp注册
uniapp注册

2.springboot代码

basedao.java

package base;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import model.User;
import util.DBUtil;
import util.ReflectUtil;

public abstract class BaseDao<T> {

    public abstract boolean add(T bean) ;
    public abstract boolean update(T bean);
    public abstract boolean delete(int id);

    public abstract T queryOne(int id);
    public abstract List<T> queryList();
    
    /**
     * 
     * @param sql
     * @param args 可变参数,即参数的数量是不固定的,本质上是数组。 可变参数只能在形参最后一个
     * @return
     */
    public boolean doADU(String sql, Object... args) {
        // 获取数据库连接
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        DBUtil dBUtil = ctx.getBean("DBUtil", DBUtil.class);
        Connection conn = dBUtil.getConnection();
        // 预处理
        PreparedStatement st = null;
        try {
            st = conn.prepareStatement(sql);
            // 绑定参数
            if (args != null) {
                // for-each循环
                for (int i = 0; i < args.length; i++) {
                    st.setObject(i + 1, args[i]);
                }
            }
            // 执行sql
            int result = st.executeUpdate();
            if (result > 0) {
                return true;
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            dBUtil.close(null, st, conn);
        }

        return false;
    }
    
    //查询操作都可用这个
    public T query(String sql, Class c, List<T> list, Object... args) {
        //String sql = "select * from user where id=?";
        // 获取数据库连接
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        DBUtil dBUtil = ctx.getBean("DBUtil", DBUtil.class);
        Connection conn = dBUtil.getConnection();
        
        // 预处理
        PreparedStatement st = null;
        try {
            st = conn.prepareStatement(sql);
            // 绑定参数
            if (args != null) {
                // for-each循环
                for (int i = 0; i < args.length; i++) {
                    st.setObject(i + 1, args[i]);
                }
            }
            // 执行sql
            ResultSet rs = st.executeQuery();
            while (rs.next()) {
                T bean = (T) ReflectUtil.createObject(c);
                //获取数据表元数据
                ResultSetMetaData md = rs.getMetaData();
                int count = md.getColumnCount();//列总数
                for(int i = 0; i < count; i++) {
                    String name = md.getColumnLabel(i + 1);//获取列名字
                    Object value = rs.getObject(name);
                    ReflectUtil.bindValue(bean, name, value);
                }
                
                if(list == null) {     //单条记录时
                    return bean;
                }
                
                list.add(bean);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            dBUtil.close(null, st, conn);
        }

        return null;
    }
    
//    添加用户
    public boolean add(String sql, Class c, Object... args) throws SQLException {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        DBUtil dBUtil = ctx.getBean("DBUtil", DBUtil.class);
        Connection conn = dBUtil.getConnection();
        
        PreparedStatement st =  conn.prepareStatement(sql);
        // 绑定参数
        if (args != null) {
            // for-each循环
            for (int i = 0; i < args.length; i++) {
                st.setObject(i + 1, args[i]);
            }
        }
        int rs = st.executeUpdate();
        if(rs == 1)
            return true;
        return false;
    }
    
    //获取行数
    public Integer getRow(String sql) throws SQLException {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        DBUtil dBUtil = ctx.getBean("DBUtil", DBUtil.class);
        Connection conn = dBUtil.getConnection();
        
        PreparedStatement st =  conn.prepareStatement(sql);
        // 绑定参数

        ResultSet rs = st.executeQuery();
        rs.last();
        return rs.getRow();
    }
    public void update() {
        // TODO Auto-generated method stub
        
    }
    public void delete() {
        // TODO Auto-generated method stub
        
    }
    public void query() {
        // TODO Auto-generated method stub
        
    }
    public User check(String uid, String password) {
        // TODO Auto-generated method stub
        return null;
    }
    
}

controller类

LoginServlet.java

package controller;

import java.io.IOException;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import dao.UserDao;
import service.UserService;
import util.DBUtil;

public class LoginServlet extends HttpServlet{
    
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //super.doGet(req, resp);
        System.out.println("doGet");
        doPost(req,resp);
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        //这里代码一般是固定
//        resp.setContentType("text/html;charset=utf-8");    
//        // 设置响应头允许ajax跨域访问
//        resp.setHeader("Access-Control-Allow-Origin", "*");
//        // 星号表示所有的异域请求都可以接受
//        resp.setHeader("Access-Control-Allow-Methods", "GET,POST");
//        
        System.out.println("dopost");
        //这里代码一般是固定
        resp.setContentType("text/html;charset=utf-8");    
        // 设置响应头允许ajax跨域访问
        resp.setHeader("Access-Control-Allow-Origin", "*");
        // 星号表示所有的异域请求都可以接受
        resp.setHeader("Access-Control-Allow-Methods", "GET,POST");
        
        //1.获取客户端提交的参数
                String uid = req.getParameter("uid");
                String password = req.getParameter("password");
                
                System.out.println("LoginServlet:"+uid+"   "+password);
                //2.调用业务逻辑
                ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
                UserService bean = ctx.getBean("UserService", UserService.class);
                
                
        //3.去到对应的页面。
                
                
                if(bean.check(uid, password) != null)
                    {

                    resp.sendRedirect(req.getContextPath()+"/success.jsp");
                    Writer out = resp.getWriter();
                    out.write("登陆成功");
                    out.close();
                System.out.println("登陆成功");}
                else
                    {resp.sendRedirect(req.getContextPath()+"/error.jsp");
                System.out.println("登陆失败");
                    }
                    
                    
                
    }
    

}

RegisterServlet.java

package controller;

import java.io.IOException;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import model.User;
import service.UserService;
import util.ReflectUtil;

/**
 * Servlet implementation class RegisterServlet
 */
public class RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegisterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        // TODO Auto-generated method stub
        System.out.println("doGet");
        doPost(req,res);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        
        resp.setContentType("text/html;charset=utf-8");    
        // 设置响应头允许ajax跨域访问
        resp.setHeader("Access-Control-Allow-Origin", "*");
        // 星号表示所有的异域请求都可以接受
        resp.setHeader("Access-Control-Allow-Methods", "GET,POST");
        
        
        
        String uname = req.getParameter("uname");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        
        System.out.println("uname:"+uname+"   "+"password:"+password+" "+"email:"+email);
        //2.调用业务逻辑
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        UserService bean = ctx.getBean("UserService", UserService.class);

        User user =  (User) ReflectUtil.createObject(User.class);
        ReflectUtil.bindValue(user, "uname", uname);
        System.out.println("user.uname="+user.getUname());
        ReflectUtil.bindValue(user, "password", password);
        ReflectUtil.bindValue(user, "email", email);
        
        if(bean.add(user) == true)
        {
            System.out.println(user.getUid());
            Writer out = resp.getWriter();
            out.write(user.getUid());
            out.close();
//            resp.sendRedirect(req.getContextPath()+"/success.jsp");
    System.out.println("注册成功");}
    else
        {resp.sendRedirect(req.getContextPath()+"/error.jsp");
    System.out.println("注册失败");
        }
    }

}

Dao层

接口UserDao.java

package dao;

import model.User;

public interface UserDao{ 
    boolean add(User bean); 
    void update(); 
    void delete(); 
    void query(); 
    
    User check(String uid,String password);
    }

实现接口UserDaoImpl.java

package daoImpl;

import java.sql.SQLException;
import java.util.List;

import base.BaseDao;
import dao.UserDao;
import model.User;
import util.ReflectUtil;

public class UserDaoImpl extends BaseDao<User> implements UserDao{

    
    public UserDaoImpl() {
        System.out.println("UserDaoImpl"); 
    }

    @Override
    public boolean add(User bean)  {
        int row;
        try {
            row = getRow("select * from user");
            System.out.println("row="+row);
            String uid = "201776431"+row;
            ReflectUtil.bindValue(bean, "uid", uid);

        } catch (SQLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        
        String sql = "insert into user(uid,uname,password,email,sSuper,delmark) values(?,?,?,?,1,1)";
        try {
            return add(sql, User.class, bean.getUid(),bean.getUname(),bean.getPassword(),bean.getEmail());
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;

    }

    @Override
    public String toString() {
        return "UserDaoImpl [queryList()=" + queryList() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode()
                + ", toString()=" + super.toString() + "]";
    }

    @Override
    public boolean update(User bean) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean delete(int id) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public User queryOne(int id) {
        String sql = "select * from user where id=?";
        return query(sql, User.class, null, id);
    }

    @Override
    public List<User> queryList() {
        // TODO Auto-generated method stub
        return null;
    }



    @Override
    public void update() {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void delete() {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void query() {
        // TODO Auto-generated method stub
        
    }

    @Override
    public User check(String uid, String password) {
        String sql = "select * from user where uid=? and password=?";
        return query(sql, User.class, null, uid,password);
    }





}

Dto层User.java

package model;

public class User {
    private String uid;
    private String uname;
    private String password;
    private Integer sSuper;
    private String email;
    private Integer delmark;
    
    
    
    
        
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getUid() {
        return uid;
    }
    public void setUid(String uid) {
        this.uid = uid;
    }
    public String getUname() {
        return uname;
    }
    public void setUname(String uname) {
        this.uname = uname;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public Integer getsSuper() {
        return sSuper;
    }
    public void setsSuper(Integer sSuper) {
        this.sSuper = sSuper;
    }
    public Integer getDelmark() {
        return delmark;
    }
    public void setDelmark(Integer delmark) {
        this.delmark = delmark;
    }
        public User(String uid, String uname, String password, String email,Integer sSuper, Integer deletemark) {
        super();
        this.uid = uid;
        this.uname = uname;
        this.password = password;
        this.email = email;
        this.sSuper = sSuper;
        this.delmark = deletemark;
        
    }
        public User() {
            
        }
        @Override
        public String toString() {
            return "User [uid=" + uid + ", uname=" + uname + ", password=" + password + ", sSuper=" + sSuper
                    + ", deletemark=" + delmark + ", getUid()=" + getUid() + ", getUname()=" + getUname()
                    + ", getPassword()=" + getPassword() + ", getsSuper()=" + getsSuper() + ", getDeletemark()="
                    + getDelmark() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()="
                    + super.toString() + "]";
        }
        
        

        
}

Service层

接口UserService.java

package service;

import model.User;

public interface UserService { 
//    boolean add(String uname,String password,String email); 
    boolean add(User bean); 
    void update();
    void delete(); 
    void query();
    User check(String uid,String password);
    
}

实现接口UserServiceImpl.java

package service;

import model.User;

public interface UserService { 
//    boolean add(String uname,String password,String email); 
    boolean add(User bean); 
    void update();
    void delete(); 
    void query();
    User check(String uid,String password);
    
}

工具类

连接数据库DBUtil.java

package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class DBUtil {
    private String username;
    private String password;
    private String url;
    private String driver;
    
    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void setDriver(String driver) {
        this.driver = driver;
    }

    
    
    
    
    public  Connection getConnection() {
        Connection conn = null;
        
        
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, username, password);
            System.out.println(conn);
        } 
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }catch (SQLException e) {
            e.printStackTrace();
        }
        
        return conn;
    }
    
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        DBUtil dBUtil = ctx.getBean("DBUtil", DBUtil.class);
        System.out.println(dBUtil.getConnection());
    }
    
    /**
     * �ر����ݿ�����
     * @param rs
     * @param st
     * @param conn
     */
    public  void close(ResultSet rs, Statement st, Connection conn) {
        if(rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(st != null) {
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

反射类ReflectUtil.java

package util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectUtil {
    /**
     * 将value绑定到obj对象的name属性
     * @param obj  对象
     * @param name  列名
     * @param value  值
     */
    public static void bindValue(Object obj, String name, Object value) {
        //获取类模板信息
        Class c = obj.getClass();
        //Class类中包含类的基本信息,属性、方法、构造方法、接口等
        /*通过名称获取属性对象
            c.getDeclaredField(name):获取声明的属性,包括私有,不包括继承过来的
            c.getField(name):获取所有属性,但不包括私有,包括继承过来的
        */
        try {
            Field f = c.getDeclaredField(name);//获取属性对象
            //强制开启访问权限
            f.setAccessible(true);
            f.set(obj, value);//指定该属性是对象obj的,且赋值为value
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    
    public static Object createObject(Class c) {
        try {
            return c.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return null;
    }
    
    public static void bindValueBySetMethod(Object obj, String name, Object value) {
        Class c = obj.getClass();
        //拼接set方法名称 set+第一个字母大写的属性名称
        String setMethod = null; //"set" + upperFirstLetter(name);
        System.out.println(setMethod);
        //获取属性
        Field f;
        try {
            f = c.getDeclaredField(name);
            Method m = c.getDeclaredMethod(setMethod, f.getType());
            //执行方法
            m.invoke(obj, value);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           https://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 注册组件,注册的组件都必须是实现类,因为spring会帮我创建组件对象,所以不能接口 -->
    <bean id="DBUtil" class="util.DBUtil">
         <property name="username"><value>root</value></property>
         <property name="password"><value>123456</value></property>
         <property name="driver"><value>com.mysql.jdbc.Driver</value></property>
         <property name="url"><value>jdbc:mysql://localhost:3306/demo?useUnicode=true&amp;characterEncoding=utf8</value></property>
    
    </bean>
    <bean id="UserDao" class="daoImpl.UserDaoImpl" ></bean>
      <bean id="UserService" class="serviceImpl.UserServiceImpl">
          <!-- ref:表示引用其它bean对象
               字面值
                   根据类型:type="" value=""
                   根据索引:index="" value=""
                   index是从0开始
           -->
          <constructor-arg ref="UserDao"></constructor-arg>
      </bean>
    
    
</beans>

3效果图

登录
登录
注册
注册

添加的一条记录

注册后添加的一条记录
注册后添加的一条记录

添加新评论

评论列表