目录:
1、验证码的工作原理:
2、Graphics类:
3、源代码:
4、运行结果:
1、验证码的工作原理:
答:(1)服务器端生成验证码——发送给客户端用户——在客户端显示——用户根据显示输入验证码——提交数据信息——服务器端进行对比验证——正确则通过验证,不正确则不通过验证
(2)验证码就是将一串随机产生的数字或符号,生成一幅图片,图片里加上一些干扰元素,由用户肉眼识别其中的验证码信息,然后输入表单提交网站验证,验证成功后才能使用某项功能。
2、Graphics类:
答:(1)Graphics类是所有图形上下文的抽象基类,允许应用程序在组件以及闭屏图像上进行绘制。
(2)常用方法:
①drawImage(Image img, int x, int y, ImageObserver observer) :绘制指定图像中当前可用的图像。
②drawString(String str, int x, int y) :使用此图形上下文的当前字体和颜色绘制由指定 string 给定的文本。
③setFont(Font font) :将此图形上下文的字体设置为指定字体。
④setColor(Color c):将此图形上下文的当前颜色设置为指定颜色。
⑤fillRect(int x, int y, int width, int height):填充指定的矩形。
x:要填充矩形的 x 坐标。
y:要填充矩形的 y 坐标。
width:要填充矩形的宽度。
height:要填充矩形的高度。
⑥drawLine(int x1, int y1, int x2, int y2) :在此图形上下文的坐标系中,使用当前颜色在点 (x1, y1) 和 (x2, y2) 之间画一条线。
x1:第一个点的 x 坐标。
y1:第一个点的 y 坐标。
x2:第二个点的 x 坐标。
y2:第二个点的 y 坐标。
⑦dispose() :释放此图形的上下文以及它使用的所有系统资源。
3、源代码:
①CodeService.java接口
package com.remoa.code.service;
public interface CodeService {
public void changeYanzhengma()throws Throwable;//改变验证码
public String gainYanzhengma()throws Throwable;//获得验证码
}
②CodeServiceImp.java
package com.remoa.code.service;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.Random;
import javax.imageio.ImageIO;
import org.springframework.stereotype.Service;
@Service
public class CodeServiceImp implements CodeService{
private String yanzhengma;
public String getYanzhengma() {
return yanzhengma;
}
public void setYanzhengma(String yanzhengma) {
this.yanzhengma = yanzhengma;
}
@Override
public void changeYanzhengma() throws Throwable {
int width = 80;//宽
int height = 40;//高
int linesNumber = 8;//干扰线数量
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
//设置背景色为白色
graphics.setColor(Color.WHITE);
//设置一个宽为80px,高为40px的矩形框
graphics.fillRect(0, 0, width, height);
//设置字体为Arial,加粗,20px的大小
graphics.setFont(new Font("Arial", Font.BOLD, 20));
Date d = new Date();
System.out.println("时间为: " + d.getTime());
Random r = new Random(d.getTime());
//设置验证码内容
String base = "QWERTYUIOPLKJHGFDSAZXCVBNM1234567890";
System.out.print("验证码为:");
StringBuffer sb = new StringBuffer();
for(int i = 0; i < 4; i++){
int number = r.nextInt(base.length());
int y = 15 + r.nextInt(20);
Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
graphics.setColor(c);
String s = String.valueOf(base.charAt(number));
graphics.drawString(s, 5 + i * width / 4, y);
sb.append(s);
}
this.setYanzhengma(sb.toString());
System.out.println(this.getYanzhengma());
System.out.println("颜色:" + graphics.getColor() + ", \n字体:" + graphics.getFont());
//设置干扰线
for(int i = 0; i < linesNumber; i++){
Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
graphics.setColor(c);
graphics.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
}
graphics.dispose();
ImageIO.write(image, "JPG", new FileOutputStream(new File("D:/apps/yanzhengma.jpg")));
}
@Override
public String gainYanzhengma() throws Throwable {
return this.getYanzhengma();
}
}
③UserAction.java
package com.remoa.user.action;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.remoa.code.service.CodeService;
import com.remoa.user.domain.UserVO;
import com.remoa.user.domain.UserValidate;
import com.remoa.user.service.UserService;
@Controller
@RequestMapping("/user")
public class UserAction {
@Autowired
private UserService service;
private UserVO user = new UserVO();
@Autowired
private CodeService codeService;
private String yanzhengma;
public UserService getService() {
return service;
}
public void setService(UserService service) {
this.service = service;
}
public UserVO getUser() {
return user;
}
public void setUser(UserVO user) {
this.user = user;
}
public String getYanzhengma() {
return yanzhengma;
}
public void setYanzhengma(String yanzhengma) {
this.yanzhengma = yanzhengma;
}
public CodeService getCodeService() {
return codeService;
}
public void setCodeService(CodeService codeService) {
this.codeService = codeService;
}
@RequestMapping("toregister.action")
public String toRegister(){
return "redirect:/user/changeyzm.action";
}
@RequestMapping(value="doregister.action", method=RequestMethod.POST)
public String register(@Valid @ModelAttribute("registerModel") UserValidate validate, BindingResult result, Model model, HttpSession session)throws Throwable{
System.out.println("----------------进入到完成注册操作的doregister.action了------------");
model.addAttribute("validate", validate);
if(result.hasErrors()){
return "user/register";
}else{
String password = validate.getUserpassword();
String checkPassword = validate.getCheckpassword();
if(password.equals(checkPassword)){
user.setUserpassword(password);
model.addAttribute("passwordNotMatch", null);
}else{
model.addAttribute("passwordNotMatch", "两次密码输入不匹配");
return "user/register";
}
String yanzhengma = validate.getYanzhengma().toUpperCase();
String checkYanzhengma = (String)session.getAttribute("checkYanzhengma");
if(yanzhengma.equals(checkYanzhengma)){
model.addAttribute("yanzhengmaNotMatch", null);
}else{
model.addAttribute("yanzhengmaNotMatch", "验证码输入错误");
return "user/register";
}
user.setUsermail(validate.getUsermail());
System.out.println(user);
service.register(user);
model.addAttribute("validate", null);
return "redirect:/user/login.action";
}
}
@RequestMapping("changeyzm.action")
public String demo(HttpSession session) throws Throwable{
codeService.changeYanzhengma();
this.yanzhengma = codeService.gainYanzhengma();
System.out.println("--------------进入到代表验证码changeyzm.action了----------" + this.yanzhengma);
session.setAttribute("checkYanzhengma", this.yanzhengma);
return "/user/register";
}
}
④测试页面register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script type="text/javascript" src="${path }/bootstrap/js/jquery.min.js" ></script>
<script type="text/javascript" src="${path }/bootstrap/js/bootstrap.min.js" ></script>
<link rel="stylesheet" href="${path }/bootstrap/css/bootstrap.min.css" />
<title>注册页面</title>
<style>
body {
font-family: "Helvetica Neue", Helvetica, Arial, "Microsoft Yahei UI", "Microsoft YaHei", SimHei, "\5B8B\4F53", simsun, sans-serif;
}
.error{
color:red;
}
</style>
</head>
<body>
<div class="col-md-7" style="text-align:center; font-size:25px">
新用户注册:
</div>
<div class="col-md-7">
<form:form class="form" action="doregister.action" modelAttribute="registerModel" method="post" role="form" >
<div class="form-group col-md-12">
<label for="usermail" class="col-md-2 control-label">
邮箱:
</label>
<div class="col-md-7">
<input type="text" name="usermail" class="form-control" value="${validate.usermail }" placeholder="请输入邮箱地址" />
</div>
<div class="col-md-3">
<form:errors path="usermail" class="error"></form:errors>
</div>
</div>
<div class="form-group col-md-12">
<label for="userpassword" class="col-md-2 control-label">
密码:
</label>
<div class="col-md-7">
<input type="password" name="userpassword" class="form-control" value="${validate.userpassword }" placeholder="设置您的登录密码" />
</div>
<div class="col-md-3">
<form:errors path="userpassword" class="error"></form:errors>
</div>
</div>
<div class="form-group col-md-12">
<label for="checkpassword" class="col-md-2 control-label">
密码确认:
</label>
<div class="col-md-7">
<input type="password" name="checkpassword" class="form-control" value="${validate.checkpassword }" placeholder="请再次输入密码" />
</div>
<div class="col-md-3">
<form:errors path="checkpassword" class="error"></form:errors>
</div>
</div>
<div class="form-group col-md-12">
<label for="yanzhengma" class="col-md-2 control-label">
验证码:
</label>
<div class="col-md-3">
<input type="text" name="yanzhengma" class="form-control" value="${validate.yanzhengma }" placeholder="请输入验证码">
</div>
<div class="col-md-3">
<img src="/images/yanzhengma.jpg" alt="验证码"/>
<a href="${path }/user/toregister.action">看不清</a>
</div>
<div class="col-md-4">
<form:errors path="yanzhengma" class="error"></form:errors>
</div>
</div>
<input type="submit" class="btn btn-success col-md-offset-3" value="提交" />
<input type="reset" class="btn btn-primary col-md-offset-1" value="重置" />
<a href="${path }/user/login.action">点此返回登录界面</a>
<p class="error">${passwordNotMatch }</p>
<p class="error">${yanzhengmaNotMatch }</p>
</form:form>
</div>
</body>
</html>