1. Basic process:
Generate a verification code page (very small) → Embed into the form → Click to refresh the page → Verify when the form is submitted.
2. Method:
1. Define TestAction and implement drawing methods
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; //Image width int height=20; //Image height BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); Graphics graphics=image.createGraphics(); graphics.setColor(this.getColor()); //Background color graphics.fillRect(0, 0, width, height); graphics.setFont(new Font("Arial",Font.BOLD,18)); graphics.setColor(this.getColor()); //The color of the word String number=String.valueOf(System.currentTimeMillis()%9000+1000); //Generate four-bit random numbers session.put("randomCode", number); //Write to the 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(); //Refresh to the page to generate image response.getOutputStream().close(); //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 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; } }Pay attention to the use of session and response
2. Register in struts.xml file:
<action name="randomCode"> </action>
No information is returned, so that the page will not be redirected
3. JSSP page writing
<%@ 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(); //The current time is used as a parameter to the url to change the URL, so that the verification code will be loaded dynamically. //It's just an interference effect, it has no meaning, but it's very clever. Haha obj.src=base+"randomCode.action?abc="+rand; //In fact, there is no abc field on the server side. } //--> </script> <title> Test Page</title> </head> <body> <form action="testLogin" method="post"> Username<input type="text" name="name"><br> Password<input type="text" name="password"><br> Verification code: <input type="text" name="chknumber" id="chknumber" maxlength="4"> <img src="<%=basePath%>randomCode.action" id="safecode" onclick="reloadcode(this,'<%=basePath%>')" /><br> <input type="submit" value="Loginin"> </form> </body> </html>4. Verification
(1) Add a verification method in Action
public String testLogin() { if(session.get("randomCode").equals(chknumber)) { return SUCCESS; } else { return ERROR; } }(2) Register in struts.xml
<action name="testLogin" method="testLogin"><result name="success">success.jsp</result><result name="error">error.jsp</result></action>
The above is the Struts2 implementation that the editor introduced to you to generate dynamic verification codes and verify the example code. I hope it will be helpful to everyone!