JavaWeb簡單使用者登入註冊例項程式碼(有驗證碼)
阿新 • • 發佈:2020-02-28
需求
- 編寫login登入介面(使用者名稱,密碼,驗證碼,登陸按鈕,註冊按鈕)
- 設計關係資料庫(編號,使用者名稱,密碼)
- 編寫註冊功能,將資料儲存在資料庫中。(姓名不能重複,設為主鍵,重複會註冊失敗)
- 編寫登入功能 。首先獲取驗證碼,先判斷驗證碼是否正確,不正確則顯示驗證碼錯誤。驗證碼正確後再獲取使用者名稱和密碼,進行資料庫的搜尋比對,若正確則重定向到成功的介面,並且將使用者名稱顯示。
jar包
技術選型
Servlet + JSP + Mysql + JDBCTemplate + Druid + BeanUtils + Tomcat
效果圖
驗證碼或者使用者名稱和密碼錯誤
Navicat Premium 顯示Mysql內容
登入成功
註冊功能
原始碼
登入主介面 login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Login</title> <script> <%-- 增加時間戳來更換驗證碼圖片 --%> window.onload=function(){ document.getElementById("img").onclick=function(){ this.src = "/daydayup/checkCodeServlet?time" + new Date().getTime(); } } <%-- 用於開啟註冊的視窗--%> function reg() { window.open("register.jsp"); } </script> <style> div{ color: red; } </style> </head> <body> <form action="/daydayup/loginServlet" method="post"> <table> <tr> <td>使用者名稱</td> <td><input type="text" name="username"></td> </tr> <tr> <td>密碼</td> <td><input type="text" name="password"></td> </tr> <tr> <td>驗證碼</td> <td><input type="text" name="checkcode"></td> </tr> <tr> <td colspan="2"><img id="img" src="/daydayup/checkCodeServlet" alt="JavaWeb簡單使用者登入註冊例項程式碼(有驗證碼)"></td> </tr> <tr> <td><input type="submit" value="登入"></td> <td><input type="button" value="註冊" onclick="reg()" ></td> </tr> </table> </form> <div>${requestScope.login_error}</div> <div>${requestScope.checkcode_error}</div> </body> </html>
註冊介面 register.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="/daydayup/registerServlet" method="post"> <table> <tr> <td>使用者名稱</td> <td><input type="text" name="username"></td> </tr> <tr> <td>密碼</td> <td><input type="text" name="password"></td> </tr> <tr> <td><input type="submit" value="確定註冊"></td> </tr> </table> </form> <div>${requestScope.register_success}</div> <div>${requestScope.register_error}</div> </body> </html>
成功介面 success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%-- <h1>${requestScope.user},歡迎您</h1> --%> <h1><%=request.getSession().getAttribute("user")%>,歡迎您</h1> </body> </html>
先編輯好JDBCUtils工具類
package cn.code.util; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; /** * JDBC工具類 使用Durid連線池 */ public class JDBCUtils { private static DataSource ds; static{ try { //載入配置檔案 Properties pro = new Properties(); //使用ClassLoader載入配置檔案,獲取位元組輸入流 InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"); pro.load(is); //初始化連線池物件 ds = DruidDataSourceFactory.createDataSource(pro); } catch (Exception e) { e.printStackTrace(); } } /** * 獲取連線池物件 */ public static DataSource getDataSource(){ return ds; } /** * 獲取連線connection物件 */ public static Connection getConnection() throws SQLException { return ds.getConnection(); } }
建立我們的使用者類實體User
package cn.code.domain; /* 使用者的實體類 */ public class User { private int id ; private String username; private String password; public int getId() { return id; } public void setId(int 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; } @Override public String toString() { return "User{" + "id=" + id + ",username='" + username + '\'' + ",password='" + password + '\'' + '}'; } }
編寫Dao來操作資料庫,裡面有login和add兩個方法 Userdao
package cn.code.dao; import cn.code.domain.User; import cn.code.util.JDBCUtils; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; /** * 操作資料庫中User表的類 */ public class UserDao { //宣告JDBCTemplate物件,以便方法公用 private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); /** * 登入方法 * * @param loginUser 目前只有使用者名稱和密碼 * @return user包含使用者全部資料 */ public User login(User loginUser) { //編寫SQL String sql = "select * from user where username = ? and password = ?"; //呼叫query方法 try { User user = template.queryForObject(sql,new BeanPropertyRowMapper<User>(User.class),loginUser.getUsername(),loginUser.getPassword()); return user; } catch (DataAccessException e) { e.printStackTrace(); return null; } } /** * 註冊方法 * * @param user 目前只包含使用者名稱和密碼 * @return 是否註冊成功 */ public boolean add(User user){ //編寫SQL String sql = "insert into user (username,password) VALUES('" + user.getUsername() + "','" + user.getPassword() + "')"; boolean flag = false; int num = 0; try { //建立資料庫連線 Connection conn = JDBCUtils.getConnection(); Statement state = null; flag = false; num = 0; state = conn.createStatement(); num = state.executeUpdate(sql); } catch (SQLException e) { e.printStackTrace(); } if(num >0) flag = true; return flag; } }
登入的Servlet
package cn.code.servlet; import cn.code.dao.UserDao; import cn.code.domain.User; 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 javax.servlet.http.HttpSession; import java.io.IOException; @WebServlet("/loginServlet") public class LoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { //設定字元編碼 request.setCharacterEncoding("utf-8"); //獲取引數 String username = request.getParameter("username"); String password = request.getParameter("password"); String checkcode = request.getParameter("checkcode"); //獲取生成的驗證碼 HttpSession session = request.getSession(); String checkcode_session =(String) session.getAttribute("checkcode_session"); //防止驗證碼儲存 刪除Session中儲存的驗證碼 session.removeAttribute("checkcode_session"); //判斷驗證碼是否正確 if(checkcode_session != null && checkcode_session.equalsIgnoreCase(checkcode)){ //equalsIgnoreCase忽略大小寫的比較 //驗證碼正確 User loginUser = new User(); loginUser.setUsername(username); loginUser.setPassword(password); User user = new UserDao().login(loginUser); if(user != null){ //使用者名稱以及密碼正確 //登入成功 //儲存使用者資訊 session.setAttribute("user",username); //因為是兩次請求,所以用Session //重定向到success.jsp response.sendRedirect(request.getContextPath()+"/success.jsp"); }else{ //使用者名稱及密碼錯誤 //登入失敗 //儲存提示資訊到request request.setAttribute("login_error","使用者名稱或密碼錯誤"); //轉發到登入頁面 request.getRequestDispatcher("/login.jsp").forward(request,response); } }else{ //驗證碼不正確 //儲存提示資訊到request request.setAttribute("checkcode_error","驗證碼錯誤"); //轉發到登入頁面 request.getRequestDispatcher("/login.jsp").forward(request,response); } } protected void doGet(HttpServletRequest request,IOException { this.doPost(request,response); } }
註冊的Servlet
package cn.code.servlet; import cn.code.dao.UserDao; import cn.code.domain.User; 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 java.io.IOException; @WebServlet("/registerServlet") public class RegisterServlet extends HttpServlet { protected void doPost(HttpServletRequest request,IOException { request.setCharacterEncoding("utf-8"); String username = request.getParameter("username"); String password = request.getParameter("password"); User registerUser = new User(); registerUser.setUsername(username); registerUser.setPassword(password); boolean flag = new UserDao().add(registerUser); if(flag) { request.setAttribute("register_success","註冊成功"); request.getRequestDispatcher("/register.jsp").forward(request,response); }else{ request.setAttribute("register_error","賬號以被註冊,註冊失敗"); request.getRequestDispatcher("/register.jsp").forward(request,response); } }
在頁面中畫驗證碼(可點選更換)Servlet
package cn.code.checkcode; import javax.imageio.ImageIO; 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 java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; //簡易驗證碼 @WebServlet("/checkCodeServlet") public class CheckCodeServlet extends HttpServlet { protected void doPost(HttpServletRequest request,IOException { int width = 100; int height = 50; //建立一物件,在記憶體中代表圖片(驗證碼圖片物件) BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR); //美化圖片 //填充背景色 Graphics g = image.getGraphics();//畫筆物件 g.setColor(Color.ORANGE); g.fillRect(0,width,height); //畫邊框 g.setColor(Color.BLUE); g.drawRect(0,width-1,height-1); String str = "QWERTYUIOPASDFGHJKLZXCVBNM1234567890zxcvbnmlkjhgfdsaqwertyuiop"; //生成隨機角標 StringBuilder sb = new StringBuilder(); Random ran = new Random(); for (int i = 1; i <= 4; i++) { int index = ran.nextInt(str.length()); //獲取字元 char ch = str.charAt(index); sb.append(ch); //寫驗證碼 g.drawString(ch+"",width/5*i,height/2); } String checkcode_session = sb.toString(); //將驗證碼存入session request.getSession().setAttribute("checkcode_session",checkcode_session); //畫干擾線 g.setColor(Color.RED); //隨機生成座標點 for (int i = 0 ;i<6;i++) { int x1 = ran.nextInt(width); int x2 = ran.nextInt(width); int y1 = ran.nextInt(height); int y2 = ran.nextInt(height); g.drawLine(x1,y1,x2,y2); } //將圖片輸出到頁面展示 ImageIO.write(image,"jpg",response.getOutputStream()); } protected void doGet(HttpServletRequest request,response); } }
到此這篇關於JavaWeb簡單使用者登入註冊例項程式碼(有驗證碼)的文章就介紹到這了,更多相關JavaWeb 使用者登入註冊內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!