1、jsp中队校验码的引用代码片段如下:
<tr>
<td align="right" > </td>
<td align="right" height="30">
<label for="verifyCode" class="yonghuming_font">
验证码:
</label>
</td>
<td height="30">
<input type="text" id="verifyCode" name="verifyCode" size="6" />
<img alt="验证码" id="safecode" src="<%=context %>/servlet/ImageServlet">
[url=javascript:reloadVerifyCode();]看不清楚[/url]
</td>
</tr>
2、javascript中(写在js文件中也是一样的)刷新图片的方法代码片段如下:
function reloadVerifyCode(){
var timenow = new Date().getTime();
document.getElementById("safecode").src="<%=request.getContextPath()%>/servlet/ImageServlet?d="+timenow;
}
3、xml文件中对图片servlet的配置,代码片段如下:
<!-- 校验码servlet -->
<servlet>
<servlet-name>ImageServlet</servlet-name>
<servlet-class>ssh.init.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImageServlet</servlet-name>
<url-pattern>/servlet/ImageServlet</url-pattern>
</servlet-mapping>
4、图片servlet代码如下:
package ssh.init;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
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;
@SuppressWarnings("serial")
public class ImageServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("***************** random picture created ****************");
this.doPost(request, response);
}
// 生成数字和字母的验证码
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// System.out.println("request path="+request.getContextPath());
//创建一个位于缓冲区的图片,长为68,高为22
BufferedImage img = new BufferedImage(68, 22,BufferedImage.TYPE_INT_RGB);
// 得到该图片的绘图对象
Graphics g = img.getGraphics();
Random r = new Random();
Color c = new Color(200, 150, 255);
g.setColor(c);
// 填充整个图片的颜色
g.fillRect(0, 0, 68, 22);
// 向图片中输出数字和字母
StringBuffer sb = new StringBuffer();
// char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
char[] ch = "abcdefghijklmnopqrstuvwxyz".toCharArray();
int index, len = ch.length;
for (int i = 0; i < 4; i++) {
index = r.nextInt(len);
g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255)));
g.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 18)); // 输出的字体和大小
g.drawString("" + ch[index], (i * 15) + 3, 18);
// 写什么数字,在图片的什么位置画
sb.append(ch[index]);
}
request.getSession(true).setAttribute("piccode", sb.toString());
ImageIO.write(img, "JPG", response.getOutputStream());
}
@SuppressWarnings("unused")
private void writeLog(String msg){
File f = new File("E:/Program Files/tomcat6.0.20/webapps/ROOT/temp.log");
if(!f.exists()){
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedWriter output = null;
try {
output = new BufferedWriter(new FileWriter(f));
} catch (IOException e) {
e.printStackTrace();
}
try {
output.write(msg);
} catch (IOException e) {
e.printStackTrace();
}
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
5、接受登录请求的Action对校验码处理的代码片段如下:
HttpServletRequest request = ServletActionContext.getRequest();
HttpSession session = request.getSession();
/**
* 验证码校验
* */
String icp = (String) session.getAttribute("piccode");
if (icp==null && !Tools.isEmpty(verifyCode)){
icp = verifyCode;
}
if(Tools.isEmpty(verifyCode)|| !icp.equalsIgnoreCase(verifyCode)){
request.setAttribute("errMessage","验证码错误,请重新输入");
return LOGIN;
}
if (!Tools.isEmpty(icp) && !Tools.isEmpty(verifyCode)) {
if (!verifyCode.equalsIgnoreCase(icp)) {
request.setAttribute("errMessage","验证码错误,请重新输入");
return LOGIN;
}
}
6、工具类Tools的代码如下:
package ssh.comm.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
public class Tools
{
public Tools()
{
}
public static boolean isEmpty(String str)
{
return str == null || str.trim().length() == 0;
}
public static boolean isEmpty(Object obj_str)
{
return obj_str == null || isEmpty(obj_str.toString());
}
public static boolean isEmpty(Object objs[])
{
return objs == null || objs.length == 0;
}
public static boolean isEmpty(String strs[])
{
if(strs == null)
return true;
String as[] = strs;
int i = 0;
for(int j = as.length; i < j; i++)
{
String str = as[i];
if(str == null || str.trim().length() == 0)
return true;
}
return false;
}
@SuppressWarnings("unchecked")
public static boolean isEmpty(Map map)
{
return map == null || map.isEmpty();
}
@SuppressWarnings("unchecked")
public static boolean isEmpty(Collection c)
{
return c == null || c.isEmpty();
}
public static boolean equals(Object src, Object dest)
{
if(src != null)
return src.equals(dest);
return src == dest;
}
public static boolean notEquals(Object src, Object dest)
{
return !equals(src, dest);
}
public static long getTodayDate()
{
Date nowDate = new Date();
String nDate = (new SimpleDateFormat("yyyyMMddHHmmss")).format(nowDate);
long endDate = Long.parseLong(nDate);
return endDate;
}
public static String formatDateTime(String dateTime)
{
if(!isEmpty(dateTime))
return dateTime.replaceAll(":", "").replaceAll("-", "").replaceAll(" ", "");
else
return dateTime;
}
public static Date stringToDate(String dateTime)
throws ParseException
{
Date date = null;
if(!isEmpty(dateTime))
{
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
date = dateformat.parse(dateTime);
return date;
} else
{
return date;
}
}
public static String getStringDate()
throws ParseException
{
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
return dateString;
}
@SuppressWarnings("unchecked")
public static String[] quChu(String arr[])
{
List list = new ArrayList();
for(int i = 0; i < arr.length; i++)
if(!list.contains(arr[i]))
list.add(arr[i]);
return (String[])list.toArray(new String[list.size()]);
}
public static String validateToStr(Object obj)
{
return obj != null ? obj.toString().trim() : "";
}
}
<tr>
<td align="right" > </td>
<td align="right" height="30">
<label for="verifyCode" class="yonghuming_font">
验证码:
</label>
</td>
<td height="30">
<input type="text" id="verifyCode" name="verifyCode" size="6" />
<img alt="验证码" id="safecode" src="<%=context %>/servlet/ImageServlet">
[url=javascript:reloadVerifyCode();]看不清楚[/url]
</td>
</tr>
2、javascript中(写在js文件中也是一样的)刷新图片的方法代码片段如下:
function reloadVerifyCode(){
var timenow = new Date().getTime();
document.getElementById("safecode").src="<%=request.getContextPath()%>/servlet/ImageServlet?d="+timenow;
}
3、xml文件中对图片servlet的配置,代码片段如下:
<!-- 校验码servlet -->
<servlet>
<servlet-name>ImageServlet</servlet-name>
<servlet-class>ssh.init.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImageServlet</servlet-name>
<url-pattern>/servlet/ImageServlet</url-pattern>
</servlet-mapping>
4、图片servlet代码如下:
package ssh.init;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
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;
@SuppressWarnings("serial")
public class ImageServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("***************** random picture created ****************");
this.doPost(request, response);
}
// 生成数字和字母的验证码
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// System.out.println("request path="+request.getContextPath());
//创建一个位于缓冲区的图片,长为68,高为22
BufferedImage img = new BufferedImage(68, 22,BufferedImage.TYPE_INT_RGB);
// 得到该图片的绘图对象
Graphics g = img.getGraphics();
Random r = new Random();
Color c = new Color(200, 150, 255);
g.setColor(c);
// 填充整个图片的颜色
g.fillRect(0, 0, 68, 22);
// 向图片中输出数字和字母
StringBuffer sb = new StringBuffer();
// char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
char[] ch = "abcdefghijklmnopqrstuvwxyz".toCharArray();
int index, len = ch.length;
for (int i = 0; i < 4; i++) {
index = r.nextInt(len);
g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255)));
g.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 18)); // 输出的字体和大小
g.drawString("" + ch[index], (i * 15) + 3, 18);
// 写什么数字,在图片的什么位置画
sb.append(ch[index]);
}
request.getSession(true).setAttribute("piccode", sb.toString());
ImageIO.write(img, "JPG", response.getOutputStream());
}
@SuppressWarnings("unused")
private void writeLog(String msg){
File f = new File("E:/Program Files/tomcat6.0.20/webapps/ROOT/temp.log");
if(!f.exists()){
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedWriter output = null;
try {
output = new BufferedWriter(new FileWriter(f));
} catch (IOException e) {
e.printStackTrace();
}
try {
output.write(msg);
} catch (IOException e) {
e.printStackTrace();
}
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
5、接受登录请求的Action对校验码处理的代码片段如下:
HttpServletRequest request = ServletActionContext.getRequest();
HttpSession session = request.getSession();
/**
* 验证码校验
* */
String icp = (String) session.getAttribute("piccode");
if (icp==null && !Tools.isEmpty(verifyCode)){
icp = verifyCode;
}
if(Tools.isEmpty(verifyCode)|| !icp.equalsIgnoreCase(verifyCode)){
request.setAttribute("errMessage","验证码错误,请重新输入");
return LOGIN;
}
if (!Tools.isEmpty(icp) && !Tools.isEmpty(verifyCode)) {
if (!verifyCode.equalsIgnoreCase(icp)) {
request.setAttribute("errMessage","验证码错误,请重新输入");
return LOGIN;
}
}
6、工具类Tools的代码如下:
package ssh.comm.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
public class Tools
{
public Tools()
{
}
public static boolean isEmpty(String str)
{
return str == null || str.trim().length() == 0;
}
public static boolean isEmpty(Object obj_str)
{
return obj_str == null || isEmpty(obj_str.toString());
}
public static boolean isEmpty(Object objs[])
{
return objs == null || objs.length == 0;
}
public static boolean isEmpty(String strs[])
{
if(strs == null)
return true;
String as[] = strs;
int i = 0;
for(int j = as.length; i < j; i++)
{
String str = as[i];
if(str == null || str.trim().length() == 0)
return true;
}
return false;
}
@SuppressWarnings("unchecked")
public static boolean isEmpty(Map map)
{
return map == null || map.isEmpty();
}
@SuppressWarnings("unchecked")
public static boolean isEmpty(Collection c)
{
return c == null || c.isEmpty();
}
public static boolean equals(Object src, Object dest)
{
if(src != null)
return src.equals(dest);
return src == dest;
}
public static boolean notEquals(Object src, Object dest)
{
return !equals(src, dest);
}
public static long getTodayDate()
{
Date nowDate = new Date();
String nDate = (new SimpleDateFormat("yyyyMMddHHmmss")).format(nowDate);
long endDate = Long.parseLong(nDate);
return endDate;
}
public static String formatDateTime(String dateTime)
{
if(!isEmpty(dateTime))
return dateTime.replaceAll(":", "").replaceAll("-", "").replaceAll(" ", "");
else
return dateTime;
}
public static Date stringToDate(String dateTime)
throws ParseException
{
Date date = null;
if(!isEmpty(dateTime))
{
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
date = dateformat.parse(dateTime);
return date;
} else
{
return date;
}
}
public static String getStringDate()
throws ParseException
{
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
return dateString;
}
@SuppressWarnings("unchecked")
public static String[] quChu(String arr[])
{
List list = new ArrayList();
for(int i = 0; i < arr.length; i++)
if(!list.contains(arr[i]))
list.add(arr[i]);
return (String[])list.toArray(new String[list.size()]);
}
public static String validateToStr(Object obj)
{
return obj != null ? obj.toString().trim() : "";
}
}