javawebday30(验证码在客户端 用当前时间来请求下一张图片 VerifyCode代码)[通俗易懂]

javawebday30(验证码在客户端 用当前时间来请求下一张图片 VerifyCode代码)[通俗易懂]页面运行servlet500错误信息tomcat报错卡住可能是因为映射错误即web.xml中的问题405post改成get方法如果出现不支持post提交可能需要修改表单中的提交方式VerifyCode.javapublicclassVerifyCode{privateintw=70;privateinth=35;…

大家好,又见面了,我是你们的朋友全栈君。

这里写图片描述
页面运行servlet 500错误信息 tomcat报错卡住 可能是因为映射错误 即 web.xml中的问题
405 post改成get方法
如果出现不支持post提交 可能需要修改 表单中的提交方式
VerifyCode.java

public class VerifyCode {
    private int w = 70;
    private int h = 35;
    private Random r = new Random();
    //{"宋体","华文楷体","黑体","微软黑体","楷体_GB2312"}
    private String [] fontNames = {
  
  "宋体","华文楷体","黑体","微软黑体","楷体_GB2312"};
    //可选字符
    private String codes = "23456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKMNOPQRSTUVWXYZ";
    //背景色
    private Color bgColor = new Color(255,255,255);
    //验证码上的文本
    private String text;
    //生成随机的颜色
    private Color randomColor(){
        int red = r.nextInt(150);
        int green = r.nextInt(150);//不能和白色过于靠近
        int blue  = r.nextInt(150);
        return new Color(red,green,blue);
    }
    //生成随机的字体
    private Font  randomFont(){
        int index = r.nextInt(fontNames.length);
        String fontName = fontNames[index];//生成随机的字体名称
        int style = r.nextInt(4);//生成随机的样式 0(无样式) 1(粗体) 2(斜体)3(粗体加斜体)
        int size = r.nextInt(5)+24;//生成随机字号
        return new Font(fontName,style,size);
    }
    //画干扰线
    private void drawLine(BufferedImage image){
        int num = 3;//一共画3条
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        for(int i=0;i<num;i++){
  
  //生成2个点的坐标,即4个值
            int x1 = r.nextInt(w);
            int y1 = r.nextInt(h);
            int x2 = r.nextInt(w);
            int y2 = r.nextInt(h);
            g2.setStroke(new BasicStroke(1.5F));
            g2.setColor(Color.blue);//干扰线是蓝色的
            g2.drawLine(x1, y1, x2, y2);//画线
        }       
    }
    //随机生成字符
    private char randomChar(){
        int index = r.nextInt(codes.length());
        return codes.charAt(index);
    }
    //创建BufferedImage
    private BufferedImage createImage(){
        BufferedImage image = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        g2.setColor(this.bgColor);
        g2.fillRect(0, 0, w, h);
        return image;
    }
    //调用这个方法得到验证码
    public BufferedImage getImage(){
        BufferedImage image = createImage();//创建图片缓冲区
        Graphics2D g2 = (Graphics2D) image.getGraphics();//得到绘制环境
        StringBuilder sb = new StringBuilder();//用来装载生成的验证码文本
        //向图片中画四个字符
        for(int i =0;i<4;i++){
  
  //循环四次,每次生成一个字符
            String s = randomChar()+"";//随机生成一个字母
            sb.append(s);//把字母添加到sb中
            float x = i*1.0F*w/4;//设置当前字符的x轴坐标
            g2.setFont(randomFont());//设置随机字体
            g2.setColor(randomColor());//设置随机颜色
            g2.drawString(s, x, h-5);//画图
        }
        this.text =sb.toString();//把生成的字符串赋给this.text
        drawLine(image);//添加干扰线
        return image;
    }

    //返回验证码图片上的文本
    public String getText(){
        return text;
    }

    //保存图片到指定的输出流
    public static void output(BufferedImage image,OutputStream out) throws IOException{
        ImageIO.write(image, "JPEG", out);
    }
}

VerifyCodeServlet.java

public class VerifyCodeServlet extends HttpServlet { 
   


    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /* * 1、生成图片 * 2、保存图片上的文本到session域中 * 3、把图片响应给客户端 */
        VerifyCode vc = new VerifyCode();
        BufferedImage bi = vc.getImage();
        request.getSession().setAttribute("session_vcode", vc.getText());//保存图片上的文本到session域

        VerifyCode.output(bi, response.getOutputStream());
    }

}

login.jsp

    <script type="text/javascript"> function _change(){ 
     /* 1、得到img元素 2、修改其src为/day28_01/VerifyCodeServlet */ var imgEle = document.getElementById("img"); //添加时间 保证每次点击不同 可以让浏览器认为是不同的请求 然后重新发送图片 防止浏览器认为已经缓存而不发 imgEle.src="/day28_01/VerifyCodeServlet?a="+new Date().getTime(); } </script>
  </head>

  <body>
   <%--本页面提供登录表单 还要显示错误信息 --%>
   <h1>登录</h1>
   <% /* 读取名为uname的cookie 如果为空显示:"" 如果不为空显示:cookie的值 */ String uname=""; Cookie[] cs = request.getCookies();//获取请求中所有的cookie if(cs!=null){//如果存在cookie for(Cookie c:cs){//循环遍历所有的cookie if("uname".equals(c.getName())){//查找名为uname的cookie uname = c.getValue();//获取这个cookie的值,给uname这个变量 } } } %>
   <% String message =""; String msg = (String)request.getAttribute("msg");//获取request域中的名为msg的属性 if(msg!=null){ message = msg; } %>
   <font color = "red"><b><%=message %></b></font>
   <form action="/day28_01/LoginServlet" method="get">
   <%--把cookie中的用户名显示到用户名文本框中 --%>
    用户名:<input type="text" name="username" value="<%=uname %>"/><br/>
    密    码:<input type="password" name="password" /><br/>
    验证码:<input type="text" name ="verifyCode" size="3"/>
            <img id="img" src="/day28_01/VerifyCodeServlet"/>
          <a href="javascript:_change()">换一张</a>
    <br/>
    <input type="submit" value="登录"/>
   </form>
  </body>

LoginServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /* * 校验验证码 * 1、从session中获取正确的验证码 * 2、从表单中获取用户填写的验证码 * 3、进行比较 * 4、如果相同,向下运行,否则保存错误信息到request域,转发到login.jsp */
        String sessionCode = (String) request.getSession().getAttribute("session_vcode");
        String paramCode = request.getParameter("verifyCode");
        if(!paramCode.equalsIgnoreCase(sessionCode)){
            request.setAttribute("msg", "验证码错误");
            request.getRequestDispatcher("/session2/login.jsp").forward(request, response);
            return;//不加return还要向下执行
        }
        /* * 1/获取表单数据 */
        //处理中文问题
        request.setCharacterEncoding("utf-8");
        //获取
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        /* * 2、校验用户名和密码是否正确 */
        if("aa".equalsIgnoreCase(username)){
  
  //登录成功
            /* * 把用户名保存到cookie中,发送给客户端浏览器 * 当再次打开login.jsp时login.jsp中会读取request中的cookie,把他显示到用户名文本框中 */
            Cookie cookie = new Cookie("uname", username);//创建Cookie
            cookie.setMaxAge(60*60*24);//设置cookie命长为1天
            response.addCookie(cookie);

            /* * 3、如果成功 * 保存用户信息到session中 * 重定向到succ1.jsp */
            HttpSession session = request.getSession();//获取session
            session.setAttribute("username", username);//向session域中保存用户名
            response.sendRedirect("/day28_01/session2/succ1.jsp");//重定向带项目名 转发不用
        }else{
  
  //登录失败
            /* * 4、如果失败 * 保存错误信息学到request域中 * 转发到login.jsp 如果重定向 域中信息获取不到 相当于2个请求了 */
            request.setAttribute("msg", "用户名或密码错误");
            RequestDispatcher rd = request.getRequestDispatcher("/session2/login.jsp");//等到转发器
            rd.forward(request,response);//转发
        }
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/159601.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)
blank

相关推荐

  • c# restsharp官网_hbase shell put

    c# restsharp官网_hbase shell putusingSystem;usingSystem.Net.Http;usingSystem.Threading.Tasks;usingSystem.Collections.Generic;usingNewtonsoft.Json;usingSystem.Net;usingSystem.IO;usingSystem.Text;usingRestSharp;namespaceHttpClientQuery{classPageInfo{publicintstar

  • mysql下载和安装详细教程

    mysql下载和安装详细教程参考链接:https://blog.csdn.net/zhujialiang18/article/details/79780131https://www.jb51.net/article/158587.htm下载安装包链接:一.MySQL的下载与安装1.下载MySQL:https://dev.mysql.com/downloads/(官网),这里我们选择社区版,如下图接下来我们选择下…

  • intellij激活码_通用破解码「建议收藏」

    intellij激活码_通用破解码,https://javaforall.cn/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

  • 强制升级openssl导致无法使用SSH(生成ssh公钥)

    最近由于工作需求要搭建freeswitch,整个过程比较纠结,遂总结于此留作备忘。起源由于我的需求是将freeswitch跑起来,所以先按照freeswitchwiki上的介绍编译freeswitch,但configure过程便遇到问题:configure:error:OpenSSL>=1.0.1eandassociateddevelopementheadersrequi…

  • ajax返回JSON时的处理方式

    ajax返回JSON时的处理方式

  • 长轮询的使用实现_python 轮询

    长轮询的使用实现_python 轮询轮询(Polling):是指不管服务器端有没有更新,客户端(通常是指浏览器)都定时的发送请求进行查询,轮询的结果可能是服务器端有新的更新过来,也可能什么也没有,只是返回个空的信息。不管结果如何,客户端处理完后到下一个定时时间点将继续下一轮的轮询。长轮询(LongPolling):长轮询的服务其客户端是不做轮询的,客户端在发起一次请求后立即挂起,一直到服务器端有更新的时候,服务器才会主动推送信息到…

    2022年10月14日

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号