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 + "]";
 }
  
}
 
本人是一個菜鳥,如有不當或錯誤之處,歡迎指正


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM