这篇文章将为大家详细讲解有关如何用Servlet和JDBC实现登陆功能,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
案例需求:访问带有验证码的登录页面login.jsp用户输入用户名,密码以及验证码。如果用户名和密码输入有误,跳转登录页面,提示:用户名或密码错误如果验证码输入有误,跳转登录页面,提示:验证码错误如果全部输入正确,则跳转到主页success.jsp,显示:用户名,欢迎您分析
步骤
文件树展示
1.配置文件和jar包在上个案例均有配置过,需要改的有:User类新增验证码成员变量,数据库增加了一个验证码字段(无用,只是为了UserDao包把查找到的数据值导入到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.验证码,画了个验证码,每次都把随机数加入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; //创建图片对象 BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //美化图片 //创建画笔 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); //写字母或数字 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类,用来判断验证码和用户名密码是否正确,注意先判断验证码;注意重定向和请求转发的不同,还有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"); //获取参数 // 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{//登陆失败,转发到登陆界面 request.setAttribute("login_error","用户名或密码不正确"); request.getRequestDispatcher("/login.jsp").forward(request,response); } }else{ //如果不正确,转发到登陆界面 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实现登陆功能就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。