Java语言实现简单的登陆注册

1.1数据库设计

create table USER_INFO(
      id number not null,
      name varchar2(20) not null,
      pass varchar2(20)
)
insert into USER_INFO values(1,'zhang','121314');

1.2 新建项目

1.2.1 添加项目说需要的包 即连接数据库的ojdbc的jar包

1.2.2编写连接数据库的工具类

package org.user.util;

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

public class DBUtil {
    private static String driver="oracle.jdbc.driver.OracleDriver";
    private static String url="jdbc:oracle:thin:@localhost:1521:orcl";
    private static String user="yongl";
    private static String passwd="121314";
    public static Connection getConnection() {
        try {
            Class.forName(driver);
            return DriverManager.getConnection(url, user, passwd);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public static void closeConn(Connection conn,Statement stm , ResultSet rs ) {

        if(stm!=null){
            try {
                stm.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(rs!=null){
            try{
                rs.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {

        System.out.println(getConnection());
    }
}

运行效果:

连接成功。

1.2.3 编写实体类

package org.user.entity;

public class User {
    private int uid;
    private String userName;
    private String userPass;
    public int getUid() {
        return uid;
    }
    public void setUid(int uid) {
        this.uid = uid;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getUserPass() {
        return userPass;
    }
    public void setUserPass(String userPass) {
        this.userPass = userPass;
    }
    @Override
    public String toString() {
        return "User [uid=" + uid + ", userName=" + userName + ", userPass=" + userPass + "]";
    }
    
    
}

1.2.4 编写dao方法

package org.user.dao;

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

import org.user.entity.User;
import org.user.util.DBUtil;

public class UserDao {
    //根据用户名查找用户
    public User findUserByName(String userName){
        //编写sql语句
        String sql="select * from USER_INFO where name=?";
        //获得连接
        Connection conn= DBUtil.getConnection();
        //有返回的结果
        ResultSet rs= null;
        //实例化一个User对象
        User user = new User();
        try {
            //用来发送sql语句的
            PreparedStatement ps = conn.prepareStatement(sql);
            //设置要传入的参数,这里是userN
            ps.setString(1, userName);
            //执行sql语句
            rs=ps.executeQuery();
            //如果能找到结果
            if(rs.next()){
                //则把找到的结果一一set进User对象中
                user.setUid(rs.getInt(1));
                user.setUserName(rs.getString(2));
                user.setUserPass(rs.getString(3));
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally {//关闭连接
            DBUtil.closeConn(conn, null, rs);
        }
        //最后要把这个user返回出去
        return user;
        
    }
    
    //添加用户
    //在这里把整个用户对象传进来
    public int addUser(User user){
        //编写sql语句
        String sql = "insert into USER_INFO values(?,?,?)";
        Connection conn= DBUtil.getConnection();
        //有返回的结果
        ResultSet rs= null;
        int i=0;
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            //这些参数是要保存到数据的
            ps.setInt(1, user.getUid());
            ps.setString(2, user.getUserName());
            ps.setString(3, user.getUserPass());
            //执行sql语句
            i=ps.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            DBUtil.closeConn(conn, null, rs);
        }
    return i;
    }
    public static void main(String[] args) {
        UserDao dao = new UserDao();
        User i = dao.findUserByName("zhang");
        System.out.println(i.getUserPass());
        
    }
}

运行结果:

1.2.5 编写servlet

a)添加用户的servlet

package org.user.servlet;

import java.io.IOException;

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 org.user.dao.UserDao;
import org.user.entity.User;

@WebServlet("/addServlet")
public class AddUserServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
     
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                //设置编码
                request.setCharacterEncoding("utf-8");
                response.setCharacterEncoding("utf-8");
                //获取从页面中提交过来的数据
                int id = Integer.parseInt(request.getParameter("id")) ;//数据类型转换
                String userName = request.getParameter("name");
                String userPass = request.getParameter("pass");    
                
                User user = new User();
                user.setUid(id);
                user.setUserName(userName);
                user.setUserPass(userPass);
                
                //调用dao方法
                UserDao dao = new UserDao();
                int i=dao.addUser(user);
                if(i==1){
                    request.getRequestDispatcher("index.jsp").forward(request, response);
                }
    }

}

b)查询用户的servlet
package org.user.servlet;

import java.io.IOException;
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 org.user.dao.UserDao;
import org.user.entity.User;
import org.user.service.LoginService;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //设置编码
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    //获取从页面中提交过来的数据
    String userName = request.getParameter("name");
    String userPass = request.getParameter("pass");
    
    LoginService service = new LoginService();
    //调用service方法 把用户名 密码传入给service
    boolean flag = service.checkUser(userName, userPass);
    String msg = flag?"success":"error";
    
    request.setAttribute("msg", msg);
    if(msg=="success"){
        request.getRequestDispatcher("index.jsp").forward(request, response);    
    }
    else{
        System.out.println("账户名或密码错误");
    }
}

}

service方法

package org.user.service;

import org.user.dao.UserDao;
import org.user.entity.User;

public class LoginService {
public boolean checkUser(String userName, String password) {
//在这里调用dao方法
UserDao dao = new UserDao();
//把名字传入对象中查询
User user = dao.findUserByName(userName);
System.out.println(user);
//山木运算 如果找到了user 并且 自己输入的password 跟数据库查出来的user.getUserPass() 一致 则返回true 否则返回false
return user != null && password.equals(user.getUserPass()) ? true : false;

    /*if(user != null){
        if(password.equals(user.getUserPass())){
            return true;
        }
    }
    return false;*/
}

}

1.2.6登陆页面
<head>
    <meta charset="utf-8">
    <title></title>
</head>

<body >
<form method="post" action="loginServlet">
     用户名:<input type="text" name="name"/><br/><br/>
     密码:<input type="password" name="pass"/><br/><br/>
     <input type="submit" > 
</form>
</body>

运行效果:

1.2.7注册页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form method="post" action="addServlet">
         学号:<input type="text" name="id"/><br/><br/>
         姓名:<input type="text" name="name"/><br/><br/>
         密码<input type="password" name="pass"/><br/><br/>
         <input type="submit" > 
    </form>
</body>
</html>


posted @ 2020-01-14 15:36  Rosemajor  阅读(1070)  评论(0编辑  收藏  举报