MVC设计模式实现登录注册功能(后端部分)

Util工具类

Util工具类的作用是将连接数据库的方式封装起来,避免重复工作,在需要进行数据库连接的时候可以直接调用该类。

 package Util;

import java.sql.*;

public class DatabaseUtils {
    private  static String username="root";//用户名
    private static String  password="123";//用户密码
    private  static String url="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=CONVERT_TO_NULL";//url路径
    public static Connection getConnection() throws ClassNotFoundException, SQLException {//该方法返回一个数据库连接
        Class.forName("com.mysql.cj.jdbc.Driver");//使用反射方式创建对象
        Connection connection=null;
        connection= DriverManager.getConnection(url,username,password);//创建数据库连接
        return  connection;//返回数据库连接
    }
    public static void release(Connection connection,   PreparedStatement preparedStatement){//用于释放数据库资源
        if(connection!=null){//判断数据库的连接状况,进行资源的释放
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            connection=null;
        }

        if(preparedStatement!=null){
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            preparedStatement=null;
        }
    }
    public static void release(Connection connection, ResultSet resultSet, PreparedStatement preparedStatement){//用于释放数据库资源
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            connection=null;
        }
        if(resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            resultSet=null;
        }
        if(preparedStatement!=null){
            try {
              preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            preparedStatement=null;
        }
    }
}

daomain层

建立实例daomain就是为了封装数据,然后作为参数传递给dao的各种方法,在Java中,将数据库中的每一个数据表都看作是一个实体类,例如daomain中的User就是我们需要查询的数据表

 package daomain;

public class User {
    private static  String account;
    private  static String password;
    private static String sex;
    private static String email;
    private static String telephone;
    public User(){

    }
    public User(String account, String password, String sex, String email, String telephone){
        this.account=account;
        this.password=password;
        this.sex=sex;
        this.email=email;
        this.telephone=telephone;
    }
    public static String getAccount() {
        return account;
    }

    public static String getEmail() {
        return email;
    }

    public static String getPassword() {
        return password;
    }

    public static String getSex() {
        return sex;
    }

    public static String getTelephone() {
        return telephone;
    }

    public static void setAccount(String account) {
        User.account = account;
    }

    public static void setEmail(String email) {
        User.email = email;
    }

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

    public static void setSex(String sex) {
        User.sex = sex;
    }

    public static void setTelephone(String telephone) {
        User.telephone = telephone;
    }

    @Override
    public String toString() {
        return "User [account=" + account + ", password=" + password +", email=" + email +", telephone=" + telephone +", sex=" + sex + "]";
    }
}

dao层

dao层被称为数据访问层,他的主要作用是实现对数据库的CRUD操作

package dao;

import Util.DatabaseUtils;
import daomain.User;

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

public class UserDaoImpl implements UserDao{
    User  user=new User();
    @Override
    public void insert(String account, String password, String email, String telephone, String sex)   {//insert方法,向数据库中插入数据
        Connection connection= null;//创建一个数据库连接并设置为空
        try {
            connection = DatabaseUtils.getConnection();//调用Util工具类来获取数据库的连接
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        PreparedStatement preparedStatement=null;//创建PreparedStatement对象,用来实现对数据库的操作,注意不可以使用Statement对象来实现,因为Statement容易产生SQL注入
        try {
            String sql="insert into test values(?,?,?,?,?)";//编写sql语句
            preparedStatement=connection.prepareStatement(sql);//预编译sql语句,这是PreparedStatment避免SQL注入的主要原因
            preparedStatement.setObject(1,account);//向占位符中添加数据
            preparedStatement.setObject(2,password);
            preparedStatement.setObject(3,email);
            preparedStatement.setObject(4,telephone);
            preparedStatement.setObject(5,sex);
        //    preparedStatement.execute();//该方法的返回值为对多少条数据产生了影响,可用来检测是否对数据库实现了修改
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DatabaseUtils.release(connection,preparedStatement);//调用工具类释放数据库资源
        }
    }

    @Override
    public boolean select(String account) {//查询数据库中的数据
         Connection connection=null;//创建数据库连接
         PreparedStatement preparedStatement=null;//创建可操作数据库的对象
        ResultSet resultSet=null;//因为对数据表的查询,会返回一个结果,因此创建一个结果集,用来存放查询结果。
        try {
            connection=DatabaseUtils.getConnection();//获取数据库连接
            String sql="select * from test where account=?";//编写sql语句
            preparedStatement=connection.prepareStatement(sql);//预编译sql语句
            preparedStatement.setObject(1,account);//向sql语句的占位符添加数据
            resultSet=preparedStatement.executeQuery();//获取查询后的结果集
            if(resultSet.next()){//获取结果集中的数据,若查询到数据,返回true,否则返回false
                return  true;
            }else {
                return  false;
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DatabaseUtils.release(connection,resultSet,preparedStatement);//释放数据库连接资源
        }
        return  false;
    }

    @Override
    public User selectUser(String account) {//获取数据表中一条数据的所有字段,其中字段对应着Java实体类的属性

         Connection connection=null;//获取数据库连接
         PreparedStatement preparedStatement=null;//创建对象
         ResultSet resultSet=null;//创建结果集
        try {
            connection =DatabaseUtils.getConnection();//获得数据库连接
            String sql="select * from test where account=? ";//编写sql语句
            preparedStatement=connection.prepareStatement(sql);//预编译sql语句
            preparedStatement.setObject(1,account);//填充占位符
            resultSet=preparedStatement.executeQuery();//获取查询结果
            while(resultSet.next()){//获取具体的数据
                user.setAccount(resultSet.getString("account"));//通过getString的关键字来获取每一条数据的字段,并将字段值赋给对象的属性
                user.setPassword(resultSet.getString("password"));
                user.setEmail(resultSet.getString("email"));
                user.setSex ( resultSet.getString("sex"));
                user.setTelephone( resultSet.getString("telephone"));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DatabaseUtils.release(connection,resultSet,preparedStatement);
        }
        return  user;
    }

    @Override
    public List<User> query() {
        return null;
    }


}

Service层

Service层就是业务层,他负责实现所有的业务,即在Service层中存在着所有的方法调用接口,可以实现所有的功能,他用来调用数据访问层即Dao层

package Service;

import dao.UserDao;
import dao.UserDaoImpl;
import daomain.User;

import java.sql.SQLException;

public class UserServiceImpl implements  UserService {
    UserDaoImpl userDao=new UserDaoImpl();
    @Override
    public void Insert(String account, String password, String email, String telephone, String sex) throws SQLException, ClassNotFoundException {
        userDao.insert(account, password, email, telephone, sex);
    }

    public Boolean select(String account) {//查询用户是否存在
        return userDao.select(account);
    }
    public User selectUser(String account) {
        return userDao.selectUser(account);
    }
}

Controller层

Controller层是用来连接前端和后端的,他用来拦截前端的请求,并将请求发送到后端,然后获取后端的响应,在将响应结果发送到前端
因为仅实现登录注册功能,因此在Controller层中只具有三个类,分别是登录,注册,显示登录结果

登录 login:

package Contraller;

import com.alibaba.fastjson.JSON;
import dao.UserDaoImpl;
import daomain.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("login")//采用注解的方式配置servlet路径
public class login extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");//首先修改request和response的字符集,避免中文乱码问题
        resp.setContentType("text/html;charset=utf-8");
        String account=req.getParameter("account");//获取请求的用户名
        String password=req.getParameter("password");//获取请求的用户密码
        UserDaoImpl userDao=new UserDaoImpl();//创建dao层的对象,用来对数据库进行操作
        User user=new User();//创建实体类,用来存放数据
        PrintWriter printWriter=resp.getWriter();//创建PrintWriter,用来发送响应信息
        if(userDao.select(account)){//查询用户是否存在
            if(userDao.selectUser(account).getPassword().equals(password)){//若存在调用selectUser方法对实体类进行赋值,同时判断数据的密码和发送来的密码是否相同,相同向前端发送0
                String jsonString= JSON.toJSONString("0");
                printWriter.append(jsonString);
            }else{
                String jsonString =JSON.toJSONString("1");//不同发送1
                printWriter.append(jsonString);
            }
        }
    }
}

注册 register:

package Contraller;

import com.alibaba.fastjson.JSON;
import dao.UserDaoImpl;
import daomain.User;
import jdk.nashorn.internal.ir.debug.JSONWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

@WebServlet("/register")
public class register extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         req.setCharacterEncoding("utf-8");//修改字符集
         resp.setContentType("text/html;charset=utf-8");
         String account=req.getParameter("account");//获取请求的所有信息,并调用dao层的数据插入方法,对数据库进行插入操作
        String password = req.getParameter("password");
        String email=req.getParameter("email");
        String telephone=req.getParameter("telephone");
        String sex=req.getParameter("sex");
        UserDaoImpl userDao=new UserDaoImpl();
        User user=new User();
        PrintWriter printWriter=resp.getWriter();
        if(userDao.select(account) ){//在插入之前先判断数据表中是否已经存在了该用户
            String jsonString = JSON.toJSONString("1");//若存在即返回1
            printWriter.write(jsonString);
        }else{//若不存在,执行插入操作,并返回0
            userDao.insert(account,password,email,telephone,sex);
            String jsonString =JSON.toJSONString("0");
            printWriter.write(jsonString);
        }
    }
}

显示登录信息

通过获取session,来得到用户的登录信息

package Contraller;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/main")
public class main extends HttpServlet {
    private  static  final  long serialVersionUID=1L;
    public  main(){
        super();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().invalidate();
        resp.sendRedirect("login.html");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        HttpSession session=req.getSession();
        PrintWriter write=resp.getWriter();
        String jsonString = JSON.toJSONString(session.getAttribute("USER"));
        System.out.println(session.getAttribute("USER"));
        write.append(jsonString);

    }
}

你可能感兴趣的:(Javaweb)