JavaWeb——登录注册功能实现

JavaWeb——登录注册功能实现

文章目录

  • JavaWeb——登录注册功能实现
    • jdbcUtils
      • druid配置文件
    • 实体类
    • Dao层(持久层)
      • BaseDao
      • UserDao接口
      • UserDaoImpl实现类
    • Service业务层
      • UserService接口
      • UserServiceImpl实现类
    • web层(Servlet)
      • 登陆的Servlet
      • 注册的Servlet

jdbcUtils

public class JDBCutils {
  public static void closeResource(Connection conn, Statement ps){
    try {

      if (ps != null) {
        ps.close();
      }
    } catch (SQLException throwables) {
      throwables.printStackTrace();
    }
    try {
      if(conn!=null){

        conn.close();
      }
    } catch (SQLException throwables) {
      throwables.printStackTrace();
    }

  }
  public static void closeResource(Connection conn, Statement ps, ResultSet rs){
    try {

      if (ps != null) {
        ps.close();
      }
    } catch (SQLException throwables) {
      throwables.printStackTrace();
    }
    try {
      if(conn!=null){

        conn.close();
      }
    } catch (SQLException throwables) {
      throwables.printStackTrace();
    }
    try {
      if(rs!=null){

        rs.close();
      }
    } catch (SQLException throwables) {
      throwables.printStackTrace();
    }
  }

  //德鲁伊连接池的封装
  public  static  Connection getConnection1(){
    Connection conn = null;
    try {
      Properties pro = new Properties();
      pro.load(JDBCutils.class.getClassLoader().getResourceAsStream("druid.properties"));
      DataSource ds = DruidDataSourceFactory.createDataSource(pro);
      conn = ds.getConnection();
//      System.out.println(conn);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
    }
    return conn;
  }

  public static void main(String[] args) {
    System.out.println(getConnection1());
  }

}

druid配置文件

  • mysql8.0配置(mysql5.0的配置有些许不同,具体看我以前的博客JDBC)
#mysql8.0配置
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=GMT%2B8
driverClassName=com.mysql.cj.jdbc.Driver
username=root
password=123456

filters=stat
initialSize=2
maxActive=300
maxWait=60000
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
validationQuery=SELECT 1
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
poolPreparedStatements=false
maxPoolPreparedStatementPerConnectionSize=200

实体类


public class User {
  private Integer id;
  private String username;
  private String password;
  private String email;

  @Override
  public String toString() {
    return "User{" +
      "id=" + id +
      ", username='" + username + '\'' +
      ", password='" + password + '\'' +
      ", email='" + email + '\'' +
      '}';
  }

  public User(Integer id, String username, String password, String email) {
    this.id = id;
    this.username = username;
    this.password = password;
    this.email = email;
  }

  public User() {
  }

  public Integer getId() {
    return id;
  }

  public void setId(Integer 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 getEmail() {
    return email;
  }

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

Dao层(持久层)

BaseDao


public class BaseDao {
 private QueryRunner queryRunner= new QueryRunner();
 //执行Insert\Update\Delete语句
  public int update(String sql,Object...args)  {
    Connection conn = JDBCutils.getConnection1();
    try {
      return queryRunner.update(conn,sql,args);
    } catch (SQLException throwables) {
      throwables.printStackTrace();
    } finally {
     JDBCutils.closeResource(conn,null);
    }

    return -1;
  }
//查询返回一个javaBean的sql语句
  public <T>T queryForone(Class<T> clazz, String sql, Object ... args){
    Connection conn = JDBCutils.getConnection1();
    try {
      return queryRunner.query(conn, sql,new BeanHandler<T>(clazz), args);
    } catch (SQLException throwables) {
      throwables.printStackTrace();
    } finally {
      JDBCutils.closeResource(conn,null);
    }
return null;
  }
//查询返回多个javaBean的sql语句
public <T> List<T> queryForList(Class<T> clazz, String sql, Object ... args){
  Connection conn = JDBCutils.getConnection1();
  try {
    return queryRunner.query(conn, sql,new BeanListHandler<T>(clazz), args);
  } catch (SQLException throwables) {
    throwables.printStackTrace();
  } finally {
    JDBCutils.closeResource(conn,null);
  }
 return null;
}
//执行一行一列的sql语句
  public Object queryForSingleValue(String sql,Object ... args){
    Connection conn = JDBCutils.getConnection1();
    try {
      return queryRunner.query(conn, sql, new ScalarHandler(),args);
    } catch (SQLException throwables) {
      throwables.printStackTrace();
    } finally {
      JDBCutils.closeResource(conn,null);
    }
return null;
  }



}

UserDao接口

public interface UserDao {
  //根据用户名查询信息
//  返回null没有这个用户
  public User queryUserByUsername(String username);

  /*保存用户信息*/
  public int saveUser(User user);
  //编写用户名和密码查询
  public User queryUsernameAndPassword(String username,String password);

}

UserDaoImpl实现类

public class UserDaoImpl extends BaseDao implements UserDao{
//查找用户
  @Override
  public User queryUserByUsername(String username) {
    String sql="select id,username,password,email from t_user where username = ?";
    return queryForone(User.class,sql,username);

  }
//注册用户
  @Override
  public int saveUser(User user) {
    String sql="insert into t_user(username,password,email)values(?,?,?)";
    return update(sql,user.getUsername(),user.getPassword(),user.getEmail());
  }

//登录用户
  @Override
  public User queryUsernameAndPassword(String username, String password) {
    String sql=" select id,username,password,email from t_user where username=? and password = ? ";

    return queryForone(User.class,sql,username,password);
  }
}

Service业务层

UserService接口

public interface UserService {
  /**
   * 注册用户
   * @param user
   */
  public  void registerUser(User user);

  /**
   *登录
   * @param user
   * @return
   */
  public  User login(User user);

  /**
   * 检查用户名是否可用
   * @param userName
   * @return 返回true则表示用户名已存在不可用,返回false则表示用户名可用
   */
  public  boolean existsUserName(String userName);

}

UserServiceImpl实现类

public class UserServiceImpl implements UserService{
private UserDao userDao=  new UserDaoImpl();
  @Override
  public void registerUser(User user) {
userDao.saveUser(user);
  }

  @Override
  public User login(User user) {

    return userDao.queryUsernameAndPassword(user.getUsername(),user.getPassword());

  }

  @Override
  public boolean existsUserName(String userName) {
    if (userDao.queryUserByUsername(userName)==null){
      return false;
    }
    return true;
  }
    
}

web层(Servlet)

登陆的Servlet


@WebServlet(name = "LoginServlet", value = "/loginServlet")
public class LoginServlet extends HttpServlet {
  private UserService userService=new UserServiceImpl();
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doPost(request, response);
  }

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //1.获取从前端传来的参数  
    String username = request.getParameter("username");
    String password = request.getParameter("password");
	//2.调用service执行业务层
    User login = userService.login(new User(null, username, password, null));

    if (login == null) {
      request.setAttribute("msg","用户名或密码错误");
      request.setAttribute("username",username);
   //3.以JSP交互形式返回前端
        request.getRequestDispatcher("pages/user/login.jsp").forward(request, response);

    }else {
     //3.以JSP交互形式返回前端 
        request.getRequestDispatcher("pages/user/login_success.jsp").forward(request, response);
    }
  }
}

注册的Servlet

@WebServlet(name = "RegistServlet", value = "/registServlet")
public class RegistServlet extends HttpServlet {
  private UserService userService=new UserServiceImpl();
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doPost(request, response);
  }

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("表单数据来了<%@ page contentType=\"text/html;charset=UTF-8\" language=\"java\" pageEncoding=\"utf-8\" %>");
    //1.获取请求参数
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String email = request.getParameter("email");
    String code = request.getParameter("code");
    //2.检查验证码是否正确
    if ("abce".equals(code)) {
      //正确
      //3.检查用户名是否可用
      if (userService.existsUserName(username)) {
        System.out.println("用户名已存在");
        request.setAttribute("msg","用户名已存在");
        request.setAttribute("username",username);
        request.setAttribute("email",email);
        request.getRequestDispatcher("/pages/user/regist.jsp").forward(request, response);
        //不可用
        //跳回注册页面
      }else{
        //可用
        //调用service保存到数据库
        userService.registerUser(new User(null,username,password,email));
        //跳到注册成功页面 regist_success
        request.getRequestDispatcher("/pages/user/regist_success.jsp").forward(request, response);

      }

    }else {
      //不正确
      //跳回注册页面
      request.setAttribute("msg","验证码错误");
      request.setAttribute("username",username);
      request.setAttribute("email",email);
      System.out.println("验证码错误");
      request.getRequestDispatcher("/pages/user/regist.jsp").forward(request, response);

    }

  }
}
  • 上述验证码是写死的,可以暂时忽略
  • 以上是基于MVC三层架构去书写,如有不懂即可评论区私信我

你可能感兴趣的:(servlet,java)