Servlet实现一个简单的登录【验证码】功能

Servlet实现一个简单的登录【验证码】功能

  • 开发工具

主要用的开发工具为 MyEclipse(2014、2016均可)、Tomcat 6.0以上、浏览器等。

  • 开发环境

开发环境为windows系统,已安装配置Java最新版开发环境。

  • 主要功能与语言

登录验证码。

所采用JSP+Servlet+JavaBean传统方式,仅限于学习使用。

  • 主要代码实现

  ValidateServlet.java(实现的功能:随机生成验证码)

ValidateServlet.java

 

import java.awt.Color;

import java.awt.Font;

import java.awt.Graphics2D;

import java.awt.image.BufferedImage;

import java.io.IOException;

import java.util.Random;

import javax.imageio.ImageIO;

import javax.servlet.ServletException;

import javax.servlet.ServletOutputStream;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

public classValidateServletextends HttpServlet {

    // 验证吗图片的宽度

    private int width = 200;;

    // 高度

    private int height = 80;

    // 验证吗的字符个数

    private int codeCount = 4;

    private int x = 0;

    // 字体高度

    private int fontHeight;

    private int codeY;

    char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H','I', 'J',

           'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V','W',

           'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8','9' };

    @Override

    public void init() throws ServletException {

       super.init();

    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)

           throws ServletException, IOException {

       // 创建一个随机数生成器类

       Random random = new Random();

       // 1、生成一幅图片。

       x = width / (codeCount + 1);

       fontHeight = height - 2;

       codeY = height - 4;

       // 定义图像buffer

       BufferedImage buffImg = new BufferedImage(width, height,

       BufferedImage.TYPE_INT_RGB);

       Graphics2D g = buffImg.createGraphics();

       // 将图像填充为白色

       g.setColor(Color.WHITE);

       g.fillRect(0, 0, width, height);

       // 创建字体,字体的大小应该根据图片的高度来定。

       Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);

       // 设置字体。

       g.setFont(font);

       // 画边框。

       g.setColor(Color.BLACK);

       g.drawRect(0, 0, width - 1, height - 1);

       // 随机产生160条干扰线,使图象中的认证码不易被其它程序探测到。

       g.setColor(Color.BLACK);

       for (int i = 0; i < 160; i++) {

           int x = random.nextInt(width);

           int y = random.nextInt(height);

           int xl = random.nextInt(12);

           int yl = random.nextInt(12);

           g.drawLine(x, y, x + xl, y + yl);

       }

       // 2、生产随机数

       // randomCode用于保存随机产生的验证码,以便用户登录后进行验证。

       StringBuffer randomCode = new StringBuffer();

       int red = 0, green = 0, blue = 0;

       // 随机产生codeCount数字的验证码。

       for (int i = 0; i < codeCount; i++) {

           // 得到随机产生的验证码数字。

           String strRand = String.valueOf(codeSequence[random.nextInt(36)]);

           // 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。

           red = random.nextInt(255);

           green = random.nextInt(255);

           blue = random.nextInt(255);

           // 用随机产生的颜色将验证码绘制到图像中。

           g.setColor(new Color(red, green, blue));

           g.drawString(strRand, (i + 1) * x, codeY);

           // 将产生的四个随机数组合在一起。

           randomCode.append(strRand);

       }

       // 3、要把随机数放在session

       // 将四位数字的验证码保存到Session中。

       HttpSession session = request.getSession();

       session.setAttribute("validateCode", randomCode.toString());

       // 4、输出图片

       // 禁止图像缓存。

       response.setHeader("Pragma", "no-cache");

       response.setHeader("Cache-Control", "no-cache");

       response.setDateHeader("Expires", 0);

       response.setContentType("image/jpeg");

       // 将图像输出到Servlet输出流中。

       ServletOutputStream out = response.getOutputStream();

       ImageIO.write(buffImg, "jpeg", out);

       out.flush();

       out.close();

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)

           throws ServletException, IOException {

       doGet(request, response);

    }

}

 

LoginServlet.java(实现的功能:实现登录功能)

 

// 首先是先判断用户输入的验证是否正确

// 然后再判断用户输入的账号密码是否正确

 

这里我没有根据数据库去查询 !只是做了个简单的测试 !判断用户输入的账号只能为:java,密码:123

如果正确则登录成功然后跳转到LoginSuccess.jsp页面!否则登录失败留在原来的页面!

LoginServlet.java

import java.io.IOException;

import java.net.URLEncoder;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

public classLoginServletextends HttpServlet {

    @Override

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)

           throws ServletException, IOException {

       // 首先是先判断用户输入的验证是否正确

       // 然后再判断用户输入的账号密码是否正确

       HttpSession session = req.getSession();

       // 获取服务器生成的验证码

       String ServiceCode = session.getAttribute("validateCode").toString();

       // 获取用户输入的的验证码

       String ClientCode = req.getParameter("codetext");

       // 验证用户输入的验证码与服务器生产的验证码是否一样

       if (ClientCode.equalsIgnoreCase(ServiceCode)) {

           // 获取用户输入的的账号

           String username = req.getParameter("username");

           // 获取用户输入的的密码

           String password = req.getParameter("password");

           // 这里我没有根据数据库去查询 !只是做了个简单的测试 !判断用户输入的账号只能为:java,密码:123

           // 如果正确则登录成功!否则登录失败

           if (username.equals("java") && password.equals("123")) {

              // 登录成功之后跳转到LoginSuccess.jsp页面!并且在页面显示username的值

              req.setAttribute("username", username);

              req.getRequestDispatcher("LoginSuccess.jsp").forward(req, resp);

           } else {

              String erro = "你输入的账号密码错误!请重新输入!";

              erro = URLEncoder.encode(erro, "utf-8");

              resp.sendRedirect("index.jsp?erro=" + erro);

           }

       } else {

           String erro = "你输入的验证码错误!请重新输入!";

           erro = URLEncoder.encode(erro, "utf-8");

           resp.sendRedirect("index.jsp?erro=" + erro);

       }

    }

    @Override

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)

           throws ServletException, IOException {

       doGet(req, resp);

    }

 

}

web.xml(关联servlet)

web.xml

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

<web-app version="2.5"

    xmlns="http://java.sun.com/xml/ns/javaee"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

     <display-name></display-name> 

      <servlet>

    <servlet-name>LoginServlet</servlet-name>

    <servlet-class>com.servlet.LoginServlet</servlet-class>

  </servlet>

  <servlet-mapping>

    <servlet-name>LoginServlet</servlet-name>

    <url-pattern>/LoginServlet</url-pattern>

     </servlet-mapping>

  

 <servlet>

    <servlet-name>ValidateServlet</servlet-name>

    <servlet-class>com.servlet.ValidateServlet</servlet-class>

  </servlet>

   <servlet-mapping>

    <servlet-name>ValidateServlet</servlet-name>

    <url-pattern>/ValidateServlet</url-pattern>

     </servlet-mapping>

  <welcome-file-list>

    <welcome-file>index.jsp</welcome-file>

  </welcome-file-list>

</web-app>

index.jsp(登录界面)

index.jsp

 

<%@ page language="java" import="java.util.*" pageEncoding="Utf-8"%>

<%@page import="java.net.URLDecoder"%>

<%

    String path = request.getContextPath();

    String basePath = request.getScheme() + "://"

           + request.getServerName() + ":" + request.getServerPort()

           + path + "/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

 

<title>My JSP 'index.jsp' starting page</title>

 

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

    <link rel="stylesheet" type="text/csshref="styles.css">

    -->

 

</head>

<script type="text/javascript">

//点击更新验证码

    function change(){

    document.getElementById("code").src="ValidateServlet?a="+newDate();

   

    }

    </script>

<body>

<span style="color: red">

   <%

  String erro=request.getParameter("erro");

 

  if(erro!=null){

   erro=new String(erro.getBytes("ISO-8859-1"),"utf-8");

  erro=URLDecoder.decode(erro, "utf-8");

  }else{

  erro="";

  }

   %>

  <%=erro %>

  </span>

    <form action="LoginServlet" method="post">

       <table>

           <tr>

              <td>用户名:</td>

              <td><input type="text" name='username' style="width:140px"></td>

              <td></td>

           </tr>

           <tr>

              <td>密码:</td>

              <td><input type="password" name='password'  style="width:140px"></td>

              <td></td>

           </tr>

           <tr>

              <td>验证码:</td>

              <td><input type="text" name='codetext' style="width:70px"> <img alt="" src="ValidateServlet" width="60px"

                  height="25px" id='code' onclick="change()"></td>

              <td><span onclick="change()">看不清,换一张</span></td>

           </tr>

           <tr>

              <td></td>

              <td><input type="submit" value="提交"> <input type="reset"value="重置"></td>

              <td></td>

           </tr>

       </table>

    </form>

</body>

</html>

                                 你输入的验证码错误!请重新输入!

                                 用户名:

                                 密码:

                                 验证码:

     

 

 

 

 

 

LoginSuccess.jsp(用户登录成功之后跳到这个页面)

LoginSuccess.jsp 

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

    <base href="<%=basePath%>">

    <title>My JSP 'LoginSuccess.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">

    <meta http-equiv="cache-control" content="no-cache">

    <meta http-equiv="expires" content="0">   

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

    <meta http-equiv="description" content="This is my page">

    <!--

    <link rel="stylesheet" type="text/csshref="styles.css">

    -->

  </head>

  <body>

    恭喜用户:${username} 成功登录!

  </body>

</html>

                          
                                                      恭喜用户:java成功登录!

 

猜你喜欢

转载自blog.csdn.net/jcy_15090250860/article/details/80331035