• 周五. 9月 30th, 2022

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

servlet-mysql实现简单用户登录注册

admin

11月 28, 2021

环境:IDEA Maven

效果截图:

项目结构:

类说明:

ConnectionUtil:负责数据库连接和释放

UserDao:数据库增删改查操作

User:用户Bean,只用注册和登录的话可以不要

UserServlet:Servlet,控制页面跳转

前端就不放了大同小异

  1 import cn.flyuz.pan.entity.User;
  2 import cn.flyuz.pan.util.Base;
  3 import cn.flyuz.pan.util.ConnectionUtil;
  4 
  5 import java.sql.Connection;
  6 import java.sql.PreparedStatement;
  7 import java.sql.ResultSet;
  8 import java.sql.SQLException;
  9 import java.util.ArrayList;
 10 import java.util.List;
 11 
 12 public class UserDao {
 13     private Connection getConn() {
 14         ConnectionUtil connectionUtil = new ConnectionUtil();
 15         return connectionUtil.getConn();
 16     }
 17     public boolean login(String user, String pw) {
 18         Connection conn = getConn();
 19         String sql = "select * from login where user=? and pw=?";
 20 
 21         try {
 22             PreparedStatement ps =conn.prepareStatement(sql);
 23             ps.setString(1,user);
 24             ps.setString(2,pw);
 25             ResultSet rs = ps.executeQuery();
 26             if (rs.next()){
 27                 ps.close();
 28                 rs.close();
 29                 return true;
 30             }
 31         } catch (SQLException e) {
 32             e.printStackTrace();
 33         }
 34         return false;
 35     }
 36 
 37     public String reg(String user, String pw) {
 38         Connection conn = getConn();
 39         String sql1= "select * from login where user = ?";
 40         String sql = "insert into login(user,pw) values (?,?)";
 41 
 42         try {
 43             PreparedStatement pss = conn.prepareStatement(sql1);
 44             pss.setString(1,user);
 45             ResultSet rs = pss.executeQuery();
 46             if (!rs.next()){
 47                 PreparedStatement ps = conn.prepareStatement(sql);
 48                 ps.setString(1,user);
 49                 ps.setString(2,pw);
 50                 ps.executeUpdate();
 51                 return Base.registerSuccess;
 52             }else{
 53                 return Base.registerFalse;
 54             }
 55         } catch (SQLException e) {
 56             e.printStackTrace();
 57         }
 58         return Base.registerFalse;
 59     }
 60 
 61     public void del(String user) {
 62         Connection conn = getConn(); //获取连接
 63         String sql = "delete from login where user = ?";//sql语句
 64         try {
 65             PreparedStatement ps = conn.prepareStatement(sql);
 66             ps.setString(1,user);
 67             ps.executeUpdate();
 68         } catch (SQLException e) {
 69             e.printStackTrace();
 70         }
 71     }
 72 //    public List<User> getAll() {
 73 //        Connection conn = getConn();
 74 //        String sql = "select * from login";
 75 //        try {
 76 //            PreparedStatement ps = conn.prepareStatement(sql);
 77 //            ResultSet rs = ps.executeQuery();
 78 //            List<User> userList = new ArrayList<>();
 79 //            while(rs.next()) {
 80 //                User user1 = new User();
 81 //                user1.setUser(rs.getString("user"));
 82 //                user1.setPw(rs.getString("pw"));
 83 //                userList.add(user1);
 84 //            }
 85 //            return userList;
 86 //        } catch (SQLException e) {
 87 //            e.printStackTrace();
 88 //        }
 89 //        return null;
 90 //    }
 91 //    public void update(String user,String pw){
 92 //        Connection conn = getConn(); //获取连接
 93 //        String sql = "update login set user = ?,pw = ? where id = ?"; //sql语句
 94 //        try {
 95 //            PreparedStatement ps = conn.prepareStatement(sql);
 96 //            //设置参数
 97 //            ps.setString(1,user);
 98 //            ps.setString(2,pw);
 99 //            ps.executeUpdate();
100 //
101 //        } catch (SQLException e) {
102 //            e.printStackTrace();
103 //        }
104 //    }
105 }

UserDao

  1 import cn.flyuz.pan.dao.UserDao;
  2 import cn.flyuz.pan.util.Base;
  3 
  4 import javax.servlet.ServletException;
  5 import javax.servlet.annotation.WebServlet;
  6 import javax.servlet.http.HttpServlet;
  7 import javax.servlet.http.HttpServletRequest;
  8 import javax.servlet.http.HttpServletResponse;
  9 import java.io.IOException;
 10 
 11 
 12 @WebServlet(name = "UserServlet", urlPatterns = "/loginServlet")
 13 public class UserServlet extends HttpServlet {
 14     private UserDao userDao = new UserDao();
 15 
 16     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 17         response.setContentType("text/html;charset=utf-8");
 18         request.setCharacterEncoding("utf-8");
 19         String type = request.getParameter("type");
 20 
 21         switch (type) {
 22             case "login":
 23                 login(request, response);
 24                 break;
 25             case "reg":
 26                 reg(request, response);
 27                 break;
 28 //            case "del":
 29 //                del(request, response);
 30 //                break;
 31 //            case "getAll":
 32 //                getAll(request, response);
 33 //                break;
 34         }
 35     }
 36     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 37         this.doPost(request, response);
 38     }
 39 
 40 
 41     private void login(HttpServletRequest request, HttpServletResponse response) {
 42         String user = request.getParameter("user");
 43         String pw = request.getParameter("pw");
 44 
 45         boolean user_login = userDao.login(user, pw);
 46         try {
 47             if (user_login) {
 48                 request.getRequestDispatcher("index/index.jsp").forward(request, response);
 49             } else {
 50                 String msg = "登陆失败";
 51                 request.getSession().setAttribute("msg", msg);
 52                 request.getRequestDispatcher("index/login.jsp").forward(request, response);
 53             }
 54         } catch (ServletException | IOException e) {
 55             e.printStackTrace();
 56         }
 57     }
 58 
 59     private void reg(HttpServletRequest request, HttpServletResponse response) {
 60         String user = request.getParameter("user");
 61         String pw = request.getParameter("pw");
 62 
 63         String rs = userDao.reg(user, pw);
 64         if (rs.equals(Base.registerSuccess)) {
 65             try {
 66                 request.getRequestDispatcher("index/login.jsp").forward(request, response);
 67             } catch (ServletException | IOException e) {
 68                 e.printStackTrace();
 69             }
 70         } else if (rs.equals(Base.registerFalse) || rs.equals(Base.registerRepeated)) {
 71             try {
 72                 String msg = "注册失败";
 73                 request.getSession().setAttribute("msg", msg);
 74                 request.getRequestDispatcher("index/register.jsp").forward(request, response);
 75             } catch (ServletException | IOException e) {
 76                 e.printStackTrace();
 77             }
 78         }
 79     }
 80 //    private void del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 81 //        String user = request.getParameter("user");
 82 //        try {
 83 //            userDao.del(user);
 84 //            request.getSession().setAttribute("msg", "删除成功!");
 85 //            request.getRequestDispatcher("index/index.jsp").forward(request, response);
 86 //        } catch (Exception e) {
 87 //            e.printStackTrace();
 88 //            request.getSession().setAttribute("msg", "删除失败!");
 89 //            request.getRequestDispatcher("index/index.jsp").forward(request, response);
 90 //        }
 91 //    }
 92 //    private void getAll(HttpServletRequest request, HttpServletResponse response) {
 93 //        request.getSession().setAttribute("userList", userDao.getAll());
 94 //        try {
 95 //            request.getRequestDispatcher("index/index.jsp").forward(request, response);
 96 //        } catch (ServletException | IOException e) {
 97 //            e.printStackTrace();
 98 //        }
 99 //    }
100 }

UserServlet

 1 import java.sql.DriverManager;
 2 import java.sql.SQLException;
 3 import java.sql.Connection;
 4 
 5 public class ConnectionUtil {
 6     private String dbDriver = "com.mysql.cj.jdbc.Driver";
 7     private String dbUrl="jdbc:mysql://localhost:3306/login?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC ";
 8     private String dbUser="root";
 9     private String dbPw="123456";
10     private static Connection conn = null;
11 
12     public Connection getConn() {
13         try{
14             Class.forName(dbDriver);
15             conn = DriverManager.getConnection(dbUrl,dbUser,dbPw);
16         }catch(ClassNotFoundException|SQLException e){
17             e.printStackTrace();
18         }
19         return conn;
20     }
21 
22     public static void conClose(){
23         if(conn != null){
24             try {
25                 conn.close();
26             } catch (SQLException e) {
27                 e.printStackTrace();
28             }
29         }
30     }
31 }

ConnectionUtil

 1 import cn.flyuz.pan.util.ConnectionUtil;
 2 
 3 import javax.servlet.ServletContextEvent;
 4 import javax.servlet.ServletContextListener;
 5 import javax.servlet.annotation.WebListener;
 6 
 7 @WebListener
 8 public class DBCloseListener implements ServletContextListener{
 9     @Override
10     public void contextDestroyed(ServletContextEvent arg0) {
11         ConnectionUtil.conClose();
12     }
13 
14     @Override
15     public void contextInitialized(ServletContextEvent arg0) {
16     }
17 }

DBCloseListener

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0"
 3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 5     <modelVersion>4.0.0</modelVersion>
 6 
 7     <groupId>groupId</groupId>
 8     <artifactId>flyuzP</artifactId>
 9     <version>1.0-SNAPSHOT</version>
10     <dependencies>
11     <dependency>
12         <groupId>javax.servlet</groupId>
13         <artifactId>jstl</artifactId>
14         <version>1.2</version>
15     </dependency>
16 
17     <dependency>
18         <groupId>taglibs</groupId>
19         <artifactId>standard</artifactId>
20         <version>1.1.2</version>
21     </dependency>
22 
23     <dependency>
24         <groupId>mysql</groupId>
25         <artifactId>mysql-connector-java</artifactId>
26         <version>8.0.12</version>
27     </dependency>
28     </dependencies>
29     <build>
30         <plugins>
31             <plugin>
32                 <groupId>org.apache.maven.plugins</groupId>
33                 <artifactId>maven-compiler-plugin</artifactId>
34                 <version>2.5</version>
35                 <configuration>
36                     <source>1.8</source>
37                     <target>1.8</target>
38                     <encoding>utf8</encoding>
39                 </configuration>
40             </plugin>
41         </plugins>
42     </build>
43 
44 </project>

Maven

发表回复

您的电子邮箱地址不会被公开。