图片验证码java代码 图片验证码java代码怎么写( 四 )


graphic.drawString(s, i * (width / 6), height - (height / 3));
}
graphic.dispose();
try {
ImageIO.write(image, imgType, output);
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
接着,创建一个servlet,用来固定图片大?。?以及处理验证码的使用场景 , 以及捕获页面生成的验证码(捕获到的二维码与用户输入的验证码一致才能通过) 。
import java.io.OutputStream;
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;
@WebServlet(urlPatterns = "/verify/regist.do" )
public class VerifyCodeServlet extends HttpServlet {
private static final long serialVersionUID = 3398560501558431737L;
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获得 当前请求 对应的 会话对象
HttpSession session = request.getSession();
// 从请求中获得 URI ( 统一资源标识符 )
String uri = request.getRequestURI();
System.out.println("hello : " + uri);
final int width = 180; // 图片宽度
final int height = 40; // 图片高度
final String imgType = "jpeg"; // 指定图片格式 (不是指MIME类型)
final OutputStream output = response.getOutputStream(); // 获得可以向客户端返回图片的输出流
// (字节流)
// 创建验证码图片并返回图片上的字符串
String code = GraphicHelper.create(width, height, imgType, output);
System.out.println("验证码内容: " + code);
// 建立 uri 和 相应的 验证码 的关联 ( 存储到当前会话对象的属性中 )
session.setAttribute(uri, code);
System.out.println(session.getAttribute(uri));
}
}
接着写一个HTML注册页面用来检验一下:
html
head
meta charset="UTF-8"
title注册/title
link rel="stylesheet" href="https://www.04ip.com/post/styles/general.css"
link rel="stylesheet" href="https://www.04ip.com/post/styles/cell.css"
link rel="stylesheet" href="https://www.04ip.com/post/styles/form.css"
script type="text/javascript" src="/images/defaultpic.gif"/script
style type="text/css"
.logo-container {
margin-top: 50px ;
}
.logo-container img {
width: 100px ;
}
.message-container {
height: 80px ;
}
.link-container {
height: 40px ;
line-height: 40px ;
}
.link-container a {
text-decoration: none ;
}
/style
/head
body
div class="container form-container"
form action="/wendao/regist.do" method="post"
div class="form" !-- 注册表单开始 --
div class="form-row"
span class="cell-1"
i class="fa fa-user"/i
/span
span class="cell-11" style="text-align: left;"
input type="text" name="username" placeholder="请输入用户名"
/span
/div
div class="form-row"
span class="cell-1"
i class="fa fa-key"/i
/span
span class="cell-11" style="text-align: left;"
input type="password" name="password" placeholder="请输入密码"
/span
/div
div class="form-row"
span class="cell-1"
i class="fa fa-keyboard-o"/i
/span
span class="cell-11" style="text-align: left;"
input type="password" name="confirm" placeholder="请确认密码"
/span
/div
div class="form-row"
span class="cell-7"
input type="text" name="verifyCode" placeholder="请输入验证码"
/span
span class="cell-5" style="text-align: center;"

推荐阅读