JavaWeb 使用Session实现一次性验证码功能

发布于 2020-7-31|标签java
复制链接
摘记: 表单 ```java 请输入验证码: ..
表单 ```java 请输入验证码: 提交 ``` 载入页面时,会自动请求getCodeServlet,获取图片(验证码)。getCodeServlet,产生验证码 ```java @WebServlet("/getCodeServlet") public class GetCodeServlet extends HttpServlet { //验证码的宽、高 private static int WIDTH=80; private static int HEIGHT=25; //绘制背景 private void drawBg(Graphics g){ //rgb g.setColor(new Color(128, 128, 128)); //绘制矩形。x,y,wigth,height g.fillRect(0,0,WIDTH,HEIGHT); //随机绘制100个干扰点 Random random=new Random(); for (int i=0;iloginServlet,处理表单 ```java @WebServlet("/loginServlet") public class LoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); HttpSession session = request.getSession(); String trueCode= (String) session.getAttribute("code"); String code=request.getParameter("code"); if (code.equals(trueCode)){ response.getWriter().write("验证码正确"); } else { response.getWriter().write("验证码错误"); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } } ``` 上面的处理方式要区分验证码的大小写。不区分大小写: ```java //先转换为全大写|全小写,再判断 trueCode=trueCode.toLowerCase(); code=code.toLowerCase(); //trueCode=trueCode.toUpperCase(); //code=trueCode.toUpperCase(); ``` 原文地址: https://www.cnblogs.com/chy18883701161/archive/2019/08/28/11423084.html
冀ICP备17029012号-4 | 版权所有©鲍亚龙 |免责声明  | GIF图库  | NUXT版