验证码,验证登录/注册,直接附代码

来源:互联网 发布:es大数据实时分析 编辑:程序博客网 时间:2024/06/14 08:53

生成验证码图片:


package com.scau.hxf;


import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;


import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class ImageServlet extends HttpServlet {


/**

*/
private static final long serialVersionUID = 1L;


/**
* Constructor of the object.
*/
public ImageServlet() {
super();
}


/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}


/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.

* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BufferedImage bImage=new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);
Graphics g=bImage.getGraphics();
Color c=new Color(200,150,255);//用于设置背景颜色
g.setColor(c);
g.fillRect(0, 0, 68, 22);//画出矩形背景

char[] ch="ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray();//验证码所有元素
Random random=new Random();
int l=ch.length,index;
StringBuffer sBuffer=new StringBuffer();
for (int i = 0; i < 4; i++) {
index=random.nextInt(l);//随机产生第几个元素的位置
g.setColor(new Color(random.nextInt(88), random.nextInt(188), random.nextInt(255)));
g.drawString(ch[index]+"", i*15+3, 18);//将元素描绘在bImage上
sBuffer.append(ch[index]);
}
request.getSession().setAttribute("picCode", sBuffer.toString());//存储验证码
ImageIO.write(bImage, "JPG", response.getOutputStream());//输出验证码
}


/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.

* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {


response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println("  <BODY>");
out.print("    This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println("  </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}


/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}


}



登录Servlet


package com.scau.hxf;


import java.io.IOException;
import java.io.PrintWriter;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class LoginServlet extends HttpServlet {


/**

*/
private static final long serialVersionUID = 1L;


/**
* Constructor of the object.
*/
public LoginServlet() {
super();
}


/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}


/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.

* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {


response.setContentType("text/html;charset=utf-8");//设置输出内容类型及编码
PrintWriter out = response.getWriter();
String picCode=(String) request.getSession().getAttribute("picCode");//获取存与request的picCode
String verifyCode=request.getParameter("verifyCode").toUpperCase();//获取用户前端输入的内容,并将内容转换为大写

if (verifyCode.equals(picCode)) {
out.print("验证码输入正确!");
} else {
out.print("验证码输入错误!!");
}
out.flush();
out.close();
}


/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.

* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {


response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println("  <BODY>");
out.print("    This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println("  </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}


/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}


}



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>Java实现验证码demo</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/css" href="styles.css">
-->
  </head>
  
  <body>
  <form action="<%= request.getContextPath()%>/servlet/LoginServlet">
     验证码:<input type="text" name="verifyCode"/>
   <img alt="验证码" id="imageCode" src="<%= request.getContextPath()%>/servlet/ImageServlet" />
   <a href="javascript:reloadCode();">看不清楚</a><br />
   <input type="submit" value="提交" />
  </form>
  </body>
  
  <script type="text/javascript">
  function reloadCode() {
  var time=new Date().getTime();
  //“?d="+time”,通过向url中传递参数破坏了浏览器的缓存机制,使得刷新成功
document.getElementById("imageCode").src="<%= request.getContextPath()%>/servlet/ImageServlet?d="+time;
}
  </script>
</html>



配置文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>java实现验证码小demo</display-name>
  <servlet>
    <description>生成验证码图片</description>
    <display-name>Auto create verify  image</display-name>
    <servlet-name>ImageServlet</servlet-name>
    <servlet-class>com.scau.hxf.ImageServlet</servlet-class>
  </servlet>
  <servlet>
    <description>检验输入验证码是否与验证码图片一致</description>
    <display-name>检验输入验证码是否与验证码图片一致</display-name>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.scau.hxf.LoginServlet</servlet-class>
  </servlet>




  <servlet-mapping>
    <servlet-name>ImageServlet</servlet-name>
    <url-pattern>/servlet/ImageServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/servlet/LoginServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>