您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關如何用Servlet和JDBC實現(xiàn)登陸功能,文章內(nèi)容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
案例需求:訪問帶有驗證碼的登錄頁面login.jsp用戶輸入用戶名,密碼以及驗證碼。如果用戶名和密碼輸入有誤,跳轉登錄頁面,提示:用戶名或密碼錯誤如果驗證碼輸入有誤,跳轉登錄頁面,提示:驗證碼錯誤如果全部輸入正確,則跳轉到主頁success.jsp,顯示:用戶名,歡迎您分析
步驟
文件樹展示
1.配置文件和jar包在上個案例均有配置過,需要改的有:User類新增驗證碼成員變量,數(shù)據(jù)庫增加了一個驗證碼字段(無用,只是為了UserDao包把查找到的數(shù)據(jù)值導入到User類不出錯)。
2.登陸界面
<%@ 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="/CaS/checkCodepic?time="+new Date().getTime(); } } </script> <style> div{ color: red; } </style> </head> <body> <form action="/CaS/loginServlet" method="post"> <table> <tr> <td>用戶名</td> <td><input type="text" name="username"></td> </tr> <tr> <td>密碼</td> <td><input type="password" name="password"></td> </tr> <tr> <td>驗證碼</td> <td><input type="text" name="checkCode"></td> </tr> <tr> <td colspan="2"><img id="img" src="/CaS/checkCodepic"></td> </tr> <tr> <td colspan="2"><input type="submit" value="登錄"></td> </tr> </table> </form> <div><%=request.getAttribute("cc_error") == null ? "" : request.getAttribute("cc_error")%></div> <div><%=request.getAttribute("login_error") == null ? "" : request.getAttribute("login_error") %></div> </body> </html>
3.驗證碼,畫了個驗證碼,每次都把隨機數(shù)加入session中以便進行對比
package Test; 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("/checkCodepic") public class CheckCodepic extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int width=100; int height=50; //創(chuàng)建圖片對象 BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //美化圖片 //創(chuàng)建畫筆 Graphics g = image.getGraphics(); //畫筆顏色 g.setColor(Color.pink); //畫個矩形,填充為粉紅色 g.fillRect(0,0,width,height); //給矩形加邊框 g.setColor(Color.blue); g.drawRect(0,0,width-1,height-1); //寫字母或數(shù)字 g.setColor(Color.green); String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; Random rd=new Random(); StringBuilder sb=new StringBuilder(); for(int i=1;i<=4;i++){ int index = rd.nextInt(str.length()); char c = str.charAt(index); sb.append(c); g.drawString(c+"",width/5*i,height/2); } String checkCode_session = sb.toString(); //將驗證碼存入session req.getSession().setAttribute("checkCode_session",checkCode_session); //加干擾線 g.setColor(Color.blue); for(int i=1;i<=10;i++){ int x1 = rd.nextInt(width); int x2 = rd.nextInt(width); int y1 = rd.nextInt(height); int y2 = rd.nextInt(height); g.drawLine(x1,y1,x2,y2); } //輸出展示 ImageIO.write(image,"jpg",resp.getOutputStream()); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); } }
4.loginServlet類,用來判斷驗證碼和用戶名密碼是否正確,注意先判斷驗證碼;注意重定向和請求轉發(fā)的不同,還有session的應用。
package Test; import Test.dao.UserDao; import Test.userclass.User; import org.apache.commons.beanutils.BeanUtils; 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; import java.lang.reflect.InvocationTargetException; import java.util.Map; @WebServlet("/loginServlet") public class loginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //設置request編碼 request.setCharacterEncoding("utf-8"); //獲取參數(shù) // String username = request.getParameter("username"); // String password = request.getParameter("password"); // String checkCode = request.getParameter("checkCode"); // User user=new User(); // user.setUsername(username); // user.setPassword(password); // user.setCheckCode(checkCode); Map<String, String[]> parameterMap = request.getParameterMap(); User user=new User(); try { BeanUtils.populate(user,parameterMap); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } UserDao userDao=new UserDao(); //先判斷驗證碼是否正確 String checkCode_session = (String)request.getSession().getAttribute("checkCode_session"); request.getSession().removeAttribute("checkCode_session"); if(checkCode_session!=null && checkCode_session.equalsIgnoreCase(user.getCheckCode())){//忽略大小寫 //如果正確,判斷用戶名密碼是否正確 User login = userDao.login(user); if(login!=null){ //登陸成功,存儲用戶信息 request.getSession().setAttribute("username",login.getUsername()); //重定向到success.jsp response.sendRedirect(request.getContextPath()+"/success.jsp"); }else{//登陸失敗,轉發(fā)到登陸界面 request.setAttribute("login_error","用戶名或密碼不正確"); request.getRequestDispatcher("/login.jsp").forward(request,response); } }else{ //如果不正確,轉發(fā)到登陸界面 request.setAttribute("cc_error","驗證碼不正確"); request.getRequestDispatcher("/login.jsp").forward(request,response); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
5.成功登陸界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h2><%=request.getSession().getAttribute("username")%>,歡迎您</h2> </body> </html>
結果
登陸界面
驗證碼錯誤情況
用戶名或密碼不正確情況
成功登陸
關于如何用Servlet和JDBC實現(xiàn)登陸功能就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。