JSP 실 용 튜 토리 얼 의 간단 한 이미지 인증 코드 실현 방법(소스 코드 첨부)
많은 초보 자 들 이 이미지 인증 코드 에 대해 잘 모 르 기 때문에 본 고 는 간단 한 JSP 애플 릿 을 통 해 인증 코드 기능 을 실현 하려 고 한다.글 에서 상세 한 예시 코드 를 제 시 했 고 문장 끝 에 완전한 실례 코드 의 다운로드 주 소 를 제 시 했 습 니 다.다음은 더 이상 할 말 이 없습니다.상세 한 소 개 를 해 보 겠 습 니 다.
효과 도
예제 코드
프론트 코드 는 다음 과 같 습 니 다.
<form action="action.jsp" method="POST">
<label> :
<input type="text" name="name" data-singleTips=" " value="admin" />
</label>
<label> : <input type="password" name="password" />
</label>
<!-- -->
<label class="captchaCode">
: <img src="img.jsp" style="cursor: pointer;" onclick="this.src=this.src + '?' + new Date().valueOf();" />
<input type="text" name="captchaImgCode" />
</label>
<div>
<input type="submit" value=" " />
</div>
</form>
인증번호 그림 은 어디에서 왔 습 니까?img.jsp 도:
<%@include file="captcha.jsp"%>
<%
init(pageContext);//
%>
그림 의 데이터 흐름 을 되 돌려 줍 니 다.action.jsp 여 기 는 사용자 이름 이나 비밀번호 검사 가 되 지 않 고 단순 인증 코드 검사 일 뿐 입 니 다.
인증 코드 를 입력 하면 다음 과 같이 표 시 됩 니 다.
반대로,포 획 된 이상 을 드 립 니 다:
action.jsp 는 captcha.jsp 에 있 는
isPass(pageContext, captchaImgCode)
방법 을 호출 하고 이상 을 포착 하 는 것 입 니 다.
<%@page pageEncoding="UTF-8"%>
<%@include file="captcha.jsp"%>
<%
String captchaImgCode = request.getParameter("captchaImgCode");
try {
if (isPass(pageContext, captchaImgCode)) {
out.println(" !");
}
} catch (Throwable e) {
out.println(e);
}
%>
핵심 captcha,jsp 코드:
<%@page pageEncoding="UTF-8" import="java.io.IOException, java.awt.*, java.awt.image.BufferedImage, java.util.Random, javax.imageio.ImageIO"%>
<%!
// Captcha
public static class Captcha {
/**
* 60
*/
private int width = 60;
/**
* 20
*/
private int height = 20;
/**
*
*/
private String code;
/**
*
*
* @return
*/
public BufferedImage get() {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);//
Graphics g;
g = image.getGraphics(); //
g.setColor(getRandColor(200, 250)); //
g.fillRect(0, 0, width, height);
g.setFont(new Font("Times New Roman", Font.PLAIN, 18)); //
g.setColor(getRandColor(160, 200));
Random random = new Random();//
for (int i = 0; i < 155; i++) {
int x = random.nextInt(width), y = random.nextInt(height);
int xl = random.nextInt(12), yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
String sRand = ""; // 4
for (int i = 0; i < 4; i++) {
String rand = String.valueOf(random.nextInt(10));
sRand += rand;
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110))); //
g.drawString(rand, 13 * i + 6, 16);// , ,
}
// SESSION
// session.setAttribute("rand", sRand);
setCode(sRand);
g.dispose();//
return image;
}
/**
*
*
* @param fc
* @param bc
* @return
*/
private Color getRandColor(int fc, int bc) {
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
Random random = new Random();
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
/**
*
*
* @return
*/
public int getHeight() {
return height;
}
/**
*
*
* @param height
*
*/
public void setHeight(int height) {
this.height = height;
}
/**
*
*
* @return
*/
public String getCode() {
return code;
}
/**
*
*
* @param code
*
*/
public void setCode(String code) {
this.code = code;
}
/**
*
*
* @return
*/
public int getWidth() {
return width;
}
/**
*
*
* @param width
*
*/
public void setWidth(int width) {
this.width = width;
}
}
/**
* SESSION
*/
public static final String SESSION_KEY = "rand";
/**
* Session
*
* @param response
*
* @param session
*
*/
public static void init(HttpServletResponse response, HttpSession session) {
Captcha img = new Captcha();
//
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpg");
try {
ImageIO.write(img.get(), "JPEG", response.getOutputStream());
/*
* , java.lang.IllegalStateException: getOutputStream() has already been called ..........
* response.getOutputStream().flush();
* response.getOutputStream().close();
* response.flushBuffer();
*/
// JSP out response.getWrite() , :1. ……
// response.getWriter();
// http://blog.sina.com.cn/s/blog_7217e4320101l8gq.html
// https://www.jb51.net/kf/201109/103284.html
// pageContext.getOut().clear();
} catch (IOException e) {
e.printStackTrace();
}
session.setAttribute(SESSION_KEY, img.getCode()); // SESSION
System.out.println(" :" + img.getCode());
}
/**
* Session(For JSP)
*
* @param pageContext
*
*/
public static void init(PageContext pageContext) {
init((HttpServletResponse) pageContext.getResponse(), pageContext.getSession());
}
/**
*
*
* @param pageContext
*
* @return true
* @throws Throwable
*/
public static boolean isPass(PageContext pageContext, String code) throws Throwable {
boolean isCaptchaPass = false;
String rand = (String) pageContext.getSession().getAttribute(SESSION_KEY);
System.out.println("rand:" + rand);
System.out.println("CaptchaCode:" + code);
if (rand == null)
throw new UnsupportedOperationException(" 。");
else if (code == null || code.equals("")) {
throw new IllegalArgumentException(" ");
} else {
isCaptchaPass = rand.equals(code);
if (!isCaptchaPass)
throw new IllegalAccessError(" ");
}
return isCaptchaPass;
}
%>
전체 코드 다운로드:http://xiazai.jb51.net/201707/yuanma/Captcha(jb51.net).rar총결산
이상 은 이 글 의 전체 내용 입 니 다.본 논문 의 내용 이 여러분 의 학습 이나 업무 에 어느 정도 도움 이 되 기 를 바 랍 니 다.궁금 한 점 이 있 으 시 면 댓 글 을 남 겨 주 셔 서 저희 에 대한 지지 에 감 사 드 립 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JSP| EL (Experession Language)텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.