• JavaWeb之Servlet登录demo


    简单的写一个注册和登录的demo

    先介绍以下流程

    (1)前台页面获取用户输入的用户名和密码

    (2)将信息发送到servlet

    (3)servlet进行数据库查询,返回查询的结果

    首先创建一个数据库,然后其中包含用户名和密码两个字段

     
    DROP TABLE IF EXISTS `user`;
    CREATE TABLE `user` (
      `password` varchar(255) CHARACTER SET utf8mb4 DEFAULT NULL,
      `username` varchar(255) DEFAULT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    -- ----------------------------
    -- Records of user
    -- ----------------------------
    INSERT INTO `user` VALUES ('123', 'yue');
    INSERT INTO `user` VALUES ('llll', '121');
     项目结构如下图,需要导入包
     前台三个页面:
    login.jsp
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>login</title>
       <style type="text/css">
     #errormsg {
      color: red;
     }
    </style>
    </head>
    <body>
     <c:if test="${not empty errormsg}">
      <p id="errormsg" >${errormsg }</p>
     </c:if>
     <form action="${pageContext.request.contextPath}/UserServlet?method=login" method="post">
      username:<input type="text" name="username" value="${username}" />
      password:<input type="password" name="password"/>
      <input type="submit" value="login" />
     </form>
     
    </body>
    </html>

     register.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>register</title>
    </head>
    <body>
       <c:if test="${not empty errormsg}">
      <p id="errormsg" >${errormsg }</p>
     </c:if>
     <form action="${pageContext.request.contextPath}/UserServlet?method=register" method="post">
      username:<input type="text" name="username" value="${username}" />
      password:<input type="password" name="password"/>
      <input type="submit" value="register" />
     </form>
    </body>
    </html>

    succ.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
     <c:choose>
       <c:when test="${empty user }">
        您还没有登陆
       </c:when>
       <c:otherwise>
        欢迎${user.username}
       </c:otherwise>
      </c:choose>
    </body>
    </html>

    DBUtil,class

    package com.hpe.util;

    import java.io.FileReader;
    import java.io.IOException;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.Properties;
    public class DBUtil {
     private static String drivatename = null;
     private static String url = null;
     private static String username = null;
     private static String password = null;
     
     static {
      try {
       //读取配置文件,加载JDBC四大参数
       Properties config = new Properties();
       config.load(new FileReader(DBUtil.class.getClassLoader().getResource("JDBC.conf").getPath()));
       drivatename = config.getProperty("drivername");
       url = config.getProperty("url");
       username = config.getProperty("username");
       password = config.getProperty("password");
       
       //System.out.println(drivatename);
       
       //加载驱动类
       Class.forName(drivatename);
      } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      } catch (ClassNotFoundException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
     }
     
     //建立连接
     public static Connection getConn() {
      Connection conn = null;
      
      try {
       conn = DriverManager.getConnection(url, username, password);
      } catch (SQLException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
      
      return conn;
     }
     
     //关闭连接
     public static void closeConn(Connection conn) {
      try {
       conn.close();
      } catch (SQLException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
     }
     
     //关闭preparedStatement
     public static void closePstmt(PreparedStatement pstmt) {
      try {
       pstmt.close();
      } catch (SQLException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
     }
     
     //关闭结果集ResultSet
     public static void closeRst(ResultSet rst) {
      try {
       rst.close();
      } catch (SQLException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
     }
    }

    JDBC.config

    drivername=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/mydbjdbc
    username=(用户)
    password=(密码)

     userServlet.java

    package com.hpe.servlet;
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import com.hpe.po.User;
    import com.hpe.service.UserService;
    public class UserServlet extends HttpServlet {
     private static final long serialVersionUID = 1L;
     private UserService service = new UserService();
        //登陆
        protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         //获取用户名和密码
         String username = request.getParameter("username");
         String password = request.getParameter("password");
         
         //调用UserService中的方法进行验证
         User user = service.login(username, password);
         if(user != null) { //登陆成功
          //将用户信息保存在域对象中
          HttpSession session = request.getSession();
          session.setAttribute("user", user);
          //转发到成功页
          request.getRequestDispatcher("/succ.jsp").forward(request, response);
         } else { // 登陆失败
          //将错误信息、用户名放入域当中
          String errormsg = "用户名或密码错误";
          request.setAttribute("errormsg", errormsg);
          request.setAttribute("username", username);
          //转发到登陆页
          request.getRequestDispatcher("/login.jsp").forward(request, response);
         }
         
        }
        //注册
        protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         String username = request.getParameter("username");
         String password = request.getParameter("password");
         
         User user = new User(username, password);
         
         //注册
         int result = service.register(user);
         if(result == 1) {//成功
          //将用户信息保存在域对象中
          HttpSession session = request.getSession();
          session.setAttribute("user", user);
          //转发到成功页
          request.getRequestDispatcher("/succ.jsp").forward(request, response);
         } else { //失败
          String errormsg = null;
          errormsg = "注册失败";
          if(result == -1)  {//
           errormsg = "该用户已经存在";
          }
          request.setAttribute("errormsg", errormsg);
          //失败转发到注册页
          request.getRequestDispatcher("/register.jsp").forward(request, response);
         }
        }
       
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      //获取method参数,根据参数选择调用的方法
      String method = request.getParameter("method");
      if(method.equals("login")) {//登陆
       login(request, response);
      } else if(method.equals("register")) {//注册
       register(request, response);
      }
     }
     
     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      doGet(request, response);
     }
    }

     UserService.class

     
    package com.hpe.service;
    import com.hpe.dao.UserDao;
    import com.hpe.po.User;
    public class UserService {
       private UserDao dao = new UserDao();
      
       public User login(String username,String password){
        return dao.findUser(username, password);
       }
      
       public int register(User user){
        User u =dao.findByName(user.getUsername());
        if(u!=null){
         return -1;
        }
        int result =dao.addUser(user);
        return result;
       }
    }
     UserDao.class
    package com.hpe.dao;
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import com.hpe.po.User;
    import com.hpe.util.DBUtil;
    import java.sql.PreparedStatement;
     
    public class UserDao {
     //登录
     public User  findUser(String username,String password)
     {
      String sql="select * from user where username=? and password=?";
      Connection conn = DBUtil.getConn();
      
      PreparedStatement pstmt = null;
      ResultSet rSet = null;
      User user = null;
      try {
       // 创建PreparedStatement
       pstmt = conn.prepareStatement(sql);
       // 设置参数
       pstmt.setString(1, username);
       pstmt.setString(2, password);
      
       rSet = pstmt.executeQuery();
       
       if (rSet.next()) {
        String name = rSet.getString(1);
        String pwd = rSet.getString(2);
        user = new User(name, pwd);
       }
      } catch (SQLException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      } finally {
       // 关闭资源 先打开的后关闭
       if (rSet != null) {
        DBUtil.closeRst(rSet);
       }
       if (pstmt != null) {
        DBUtil.closePstmt(pstmt);
       }
       if (conn != null) {
        DBUtil.closeConn(conn);
       }
      }
      return user;
     }
     
     public User findByName(String username){
      String sql = "select * from user where username=?";
      // 创建连接
      Connection conn = DBUtil.getConn();
      PreparedStatement pstmt = null;
      ResultSet rSet = null;
      User user = null;
      try {
       // 创建PreparedStatement
       pstmt = conn.prepareStatement(sql);
       // 设置参数
       pstmt.setString(1, username);
       // 运行SQL语句
       /*
        * 增 删 改 executeUpdate() 查询 executeQuery()
        */
       rSet = pstmt.executeQuery();
       // 处理结果
       if (rSet.next()) {
        String name = rSet.getString(1);
        String pwd = rSet.getString(2);
        user = new User(name, pwd);
       }
      } catch (SQLException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      } finally {
       // 关闭资源 先打开的后关闭
       if (rSet != null) {
        DBUtil.closeRst(rSet);
       }
       if (pstmt != null) {
        DBUtil.closePstmt(pstmt);
       }
       if (conn != null) {
        DBUtil.closeConn(conn);
       }
      }
      
      return user;
     }
     
     public int addUser(User user) {
      // SQL语句
      String sql = "insert into user values(?, ?)";
      // 创建连接
      Connection conn = DBUtil.getConn();
      PreparedStatement pstmt = null;
      int result = 0;
      
      try {
       // 创建PreparedStatement
       pstmt = conn.prepareStatement(sql);
       // 设置参数
       pstmt.setString(1, user.getUsername());
       pstmt.setString(2, user.getPassword());
       // 运行SQL语句
       /*
        * 增 删 改 executeUpdate() 查询 executeQuery()
        */
       result = pstmt.executeUpdate();
      } catch (SQLException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      } finally {
       // 关闭资源 先打开的后关闭
       if (pstmt != null) {
        DBUtil.closePstmt(pstmt);
       }
       if (conn != null) {
        DBUtil.closeConn(conn);
       }
      }
      return result;
     }
    }
     
    package com.hpe.po;
    public class User {
     private String username;
     private String password;
     
     public User(){
      
     }
     public User(String username, String password) {
      super();
      this.username = username;
      this.password = password;
     }
     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;
     }
     @Override
     public String toString() {
      return "User [username=" + username + ", password=" + password + "]";
     }
      
    }
     
    本人是一个菜鸟,如有不当或错误之处,欢迎指正
  • 相关阅读:
    Linux 配置中文环境
    CookieContainer 丢失Cookie
    h5调用摄像头
    网络编程之Reactor 模式
    图形化命令行工具:
    关于VSTO调用Excel后进程无法退出的解决方案:
    ActionLink()与jquery更好地结合建造MVC网页:
    实现一个特殊栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作
    用数组结构实现大小固定的栈和队列
    比较器整理
  • 原文地址:https://www.cnblogs.com/Syue/p/9410592.html
Copyright © 2020-2023  润新知