zoukankan      html  css  js  c++  java
  • 案例9 -实现验证码功能

    1 改写jsp代码

    2 编写自动生成验证码的servlet

    直接使用模板

    3 实现点击动态改变

    <script type="text/javascript">
        function changeImg(obj) {
            obj.src="${pageContext.request.contextPath }/checkImg?time="+new Date().getTime();
        }
    </script>

    4 实现验证码的校验功能

    package www.test.web.servlet;
    
    import java.io.IOException;
    import java.sql.SQLException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import www.test.domain.User;
    import www.test.service.LoginService;
    
    public class LoginServlet extends HttpServlet {
    
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
            // 解决乱码问题
            request.setCharacterEncoding("UTF-8");
    
            // 获得页面输入的验证
            String checkCode_client = request.getParameter("checkCode");
            // 获得生成图片的文字的验证码
            String checkCode_session = (String) request.getSession().getAttribute("checkcode_session");
            // 比对页面的和生成图片的文字的验证码是否一致
            if (!checkCode_session.equals(checkCode_client)) {
                request.setAttribute("loginInfo", "您的验证码不正确");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
                return; //验证码输入错误的话,就没有必要获取输入的用户名和密码
            }
            // 获取用户输入的数据  
            String username = request.getParameter("username");
            String password = request.getParameter("password");
    
            LoginService service = new LoginService();
            User user = null;
            try {
                user = service.findUser(username, password);
            } catch (SQLException e) {
    
                e.printStackTrace();
            }
    
            if (user != null) {
                response.sendRedirect("/WEBTest24/index.jsp");
            } else {
                request.getRequestDispatcher("/login.jsp").forward(request, response);
                ;
            }
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    
    }
    <div id="checkCodeInfo" style="color:red">${loginInfo}</div> 
  • 相关阅读:
    php抽象类,接口,特性的比较
    服务器和客户端缓存控制
    git平时用到的仓库
    PHP版DES算法加密数据
    Linux连接Windows服务器以及文件传输方法
    php连接MySQL数据库的三种方式(mysql/mysqli/pdo)
    PHP实现网站访客来访显示访客IP&浏览器&操作系统
    ESXI的使用
    vue
    Laravel学习笔记
  • 原文地址:https://www.cnblogs.com/jepson6669/p/8407056.html
Copyright © 2011-2022 走看看