servlet实现验证码登录

//用户登录HTML页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户登录</title>
</head>
<body>
    <form action="/web01/judge" method="post">
        <div style="background-color: powderblue;height: 350px ;width: 300px;margin: auto" >
            <br>
            <h3 style="text-align: center;">登录界面</h3><br/>
            <div style="text-align: center">
                用户名:<input type="text" placeholder="请输入用户名" name="username" />
                        <span style="color: red">*</span> <br/><br/>
                密  &nbsp&nbsp码:<input type="password" placeholder="请输入密码" name="password"/>
                <span style="color: red">*</span><br/><br>
                <!--验证码-->
                <img src="/web01/login" width="100" height="35"  id="img" onclick="change(this)">
                <a href="javascript:change()">换一张</a>
                <br/>
                验证码:<input type="text" name="yzm" placeholder="请输入验证码">
                <span style="color: red">*</span><br/><br/>
                <button type="submit" style="background-color: coral" >登录</button>

            </div>

        </div>
    </form>
<script>
//点击图片更新验证码
    function  change(img) {
        img.src=img.src+"?"+new Date().getTime();
    }
//点击下一张更新有验证码
    function  change() {
        var i= document.getElementById("img");
        i.src=i.src+"?"+new Date().getTime();
    }
</script>

</body>
</html>

---------------------------------------------------------------------------------------

//获取验证码的servlet页面

package com.westos.web01.servlet;

import org.apache.commons.lang3.RandomUtils;

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 javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

@WebServlet(name = "YzmServlet")
public class YzmServlet extends HttpServlet {
    String str="";
    private static final int WIDTH = 100;
    private static final int HEIGHT = 40;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("image/jpg");

        //产生一张图片
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        //填充背景
        g.fillRect(0, 0, WIDTH, HEIGHT);

        //设置背景色
        g.setColor(Color.WHITE);

        //设置前景色
        g.setColor(Color.RED);

        //设置字体
        Font font = new Font("微软雅黑", Font.BOLD, 20);
        g.setFont(font);

        //获取随机字母
        str= genRandomString(4);

                //验证码传
        HttpSession session = request.getSession();
        session.setAttribute("d",str);


        //绘制验证码
        g.drawString(str, 10, 30);

        //绘制点
        for (int i = 0; i < 200; i++) {
            int x = RandomUtils.nextInt(0, WIDTH);
            int y = RandomUtils.nextInt(0, HEIGHT);
            Color color = new Color(RandomUtils.nextInt(0, 255), RandomUtils.nextInt(0, 255), RandomUtils.nextInt(0, 255));
            g.setColor(color);
            g.drawLine(x, y, x, y);
        }
        //绘制直线
        for (int i = 0; i < 15; i++) {
            int x1 = RandomUtils.nextInt(0, WIDTH);
            int x2 = RandomUtils.nextInt(0, WIDTH);
            int y1 = RandomUtils.nextInt(0, HEIGHT);
            int y2 = RandomUtils.nextInt(0, HEIGHT);
            Color color = new Color(RandomUtils.nextInt(0, 255), RandomUtils.nextInt(0, 255), RandomUtils.nextInt(0, 255));
            g.setColor(color);
            g.drawLine(x1, y1, x2, y2);
        }
        //输出图片
         ImageIO.write(image, "jpg", response.getOutputStream());

//        ImageIO.write(image,"jpg",new File("e:\\yzm.jpg"));


    }

    private String genRandomString(int len) {
        String result = "";
        //获取len个验证码字母
        for (int i = 0; i < len; i++) {
            char c = (char) RandomUtils.nextInt(65, 91);

            result = result + c ;

        }
        return result;
    }
}


-----------------------------------------------------------------------------------
//判断用户信息输入是否正确


package com.westos.web01.servlet;

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 javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "JudgeServlet")
public class JudgeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");

        //设置用户名和密码
        String myusername="用户";
        String mypassword="666";

        //获取输入框中的用户名、密码及验证码
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        String yzm=request.getParameter("yzm");

        //验证码接收
        HttpSession session = request.getSession();
        String s=(String) session.getAttribute("d");
        //判断登录是否正确
             if((myusername.equals(username))&&(mypassword.equals(password))&&(yzm.equalsIgnoreCase(s))&&(yzm!=null)&&(s!=null)){
                response.getWriter().println(" <script>\n" +
                        "                    alert(\"登录成功!!!!\")\n" +
                        "                </script>");
                response.getWriter().println("<h1 style=\"text-align: center\">登录成功后的界面</h1>");
            }else
                 if(username==""||password==""||yzm==""){
                     response.getWriter().println("  <script>\n" +
                             "                    alert(\"输入不能为空!\")\n" +
                             "                </script>");
                     response.getWriter().println("");
                 }else
                     if((myusername.equals(username))&&(mypassword.equals(password))&&(!yzm.equalsIgnoreCase(s))) {
                         response.getWriter().println(" <script>\n" +
                                 "                    alert(\"验证码错误,请重新输入!\")\n" +
                                 "                </script>");
                     }
             else
                 response.getWriter().println(" <script>\n" +
                         "                       alert(\"用户名和密码不匹配!\")\n" +
                         "                   </script>");

    }
}

----------------------------------------------------------------------------------

//配置servlet


<?xml version="1.0" encoding="UTF-8"?>

<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -->

        <web-app metadata-complete="true" version="3.0" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee">

    <display-name>java web01</display-name>

    <description> java web01 </description>


    <servlet>
        <servlet-name>YzmServlet</servlet-name>
        <servlet-class>com.westos.web01.servlet.YzmServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>YzmServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>

<servlet>
    <servlet-name>JudgeServlet</servlet-name>
    <servlet-class>com.westos.web01.servlet.JudgeServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>JudgeServlet</servlet-name>
    <url-pattern>/judge</url-pattern>
</servlet-mapping>
</web-app>

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值