Struts2는 동적 인증 코드를 생성하고 인스턴스 코드를 검증합니다.
인증 코드 페이지가 생성됩니다 (매우 작음) → 폼에 삽입됩니다 → 누르면 페이지를 새로 고칠 수 있습니다 → 폼 제출 시 검증됩니다.
2. 방법:
1. TestAction 정의, 그림 그리기 방법 구현
package com.zhuguang.action;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class TestAction extends ActionSupport implements SessionAware,ServletResponseAware
{
private Map<String, Object> session;
private HttpServletResponse response;
private static final long serialVersionUID = 1L;
private String chknumber;
@Override
public String execute() throws Exception
{
response.setHeader("Cache-Control", "no-cache");
int width=50; //
int height=20; //
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics graphics=image.createGraphics();
graphics.setColor(this.getColor()); //
graphics.fillRect(0, 0, width, height);
graphics.setFont(new Font("Arial",Font.BOLD,18));
graphics.setColor(this.getColor()); //
String number=String.valueOf(System.currentTimeMillis()%9000+1000); //
session.put("randomCode", number); // session
graphics.drawString(number, (int)(width*0.1), (int)(height*0.8));
graphics.dispose();
JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(response.getOutputStream());
encoder.encode(image);
response.getOutputStream().flush(); //
response.getOutputStream().close(); // writer
return null;
}
private Color getColor(){
int red=(int)(Math.random()*1000%256);
int green=(int)(Math.random()*1000%256);
int blue=(int)(Math.random()*1000%256);
return new Color(red,green,blue);
}
public String getChknumber()
{
return chknumber;
}
public void setChknumber(String chknumber)
{
this.chknumber = chknumber;
}
@Override
public void setSession(Map<String, Object> session)
{
// TODO Auto-generated method stub
this.session = session;
}
@Override
public void setServletResponse(HttpServletResponse response)
{
// TODO Auto-generated method stub
this.response = response;
}
}
세션과response에 사용2. struts에서.xml 파일에 등록:
<action name="randomCode" class="com.zhuguang.action.TestAction">
</action>
그 중 어떤 정보도 되돌려 주지 않으면 페이지를 뛰어넘지 않는다3. jsp 페이지 작성
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!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">
<script type="text/javascript">
<!--
function reloadcode(obj,base){
var rand=new Date().getTime(); // url , URL , ,
// , , ,
obj.src=base+"randomCode.action?abc="+rand; // abc 。
}
//-->
</script>
<title> </title>
</head>
<body>
<form action="testLogin" method="post">
Username<input type="text" name="name"><br>
Password<input type="text" name="password"><br>
:<input type="text" name="chknumber" id="chknumber" maxlength="4" class="chknumber_input">
<img title=" " width="50" height="20" src="<%=basePath%>randomCode.action" id="safecode" onclick="reloadcode(this,'<%=basePath%>')" /><br>
<input type="submit" value="Loginin">
</form>
</body>
</html>
4. 검증(1) Action에 인증 방법 추가
public String testLogin()
{
if(session.get("randomCode").equals(chknumber))
{
return SUCCESS;
}
else
{
return ERROR;
}
}
(2)struts.xml에서 등록
<action name="testLogin" class="com.zhuguang.action.TestAction" method="testLogin">
<result name="success">success.jsp</result>
<result name="error">error.jsp</result>
</action>
위에서 말한 것은 여러분께 소개해 드린 Struts2는 동적 검증 코드를 생성하고 실례 코드를 검증하는 것을 실현하여 여러분께 도움이 되기를 바랍니다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
한 편의 문장으로 Struts2의 유형 전환을 해결하다우리는 HTTP를 통해 백그라운드에 제출된 데이터가 모두 문자열의 형식이라는 것을 알고 있으며, 우리가 필요로 하는 데이터 형식은 당연히 문자열 형식 하나만 있는 것이 아니다.그래서 우리는 유형 전환이 필요하다!다음...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.