您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“JavaWeb如何實現用戶登錄注冊”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“JavaWeb如何實現用戶登錄注冊”這篇文章吧。
需求
編寫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=""></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> <%-- <h2>${requestScope.user},歡迎您</h2> --%> <h2><%=request.getSession().getAttribute("user")%>,歡迎您</h2> </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, HttpServletResponse response) throws ServletException, 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, HttpServletResponse response) throws ServletException, 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); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(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, HttpServletResponse response) throws ServletException, 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,0,width,height); //畫邊框 g.setColor(Color.BLUE); g.drawRect(0,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, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
以上是“JavaWeb如何實現用戶登錄注冊”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。