1、编写一个类实现com.opensymphony.xwork2.Result,或者继承org.apache.struts2.dispatcher.StrutsResultSupport
2、自定义的结果视图,必须先声明后才能使用
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"><struts> <constant name="struts.devMode" value="true" /> <package name="p1" extends="struts-default"> <result-types> <result-type name="captcha" class="com.itheima.results.CaptchaResult"></result-type> </result-types> <action name="genCaptcha"> <result name="success" type="captcha"> <param name="width">200</param> <param name="height">50</param> </result> </action> </package></struts>
servlet验证码代码:
import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.io.IOException;import java.util.Random;import javax.imageio.ImageIO;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class AuthCodeDemo1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int width=120,height=25; //1.在内存生成一个图片 BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //2.得到画笔 Graphics g = img.getGraphics(); //3.画一个矩形框 g.setColor(Color.BLUE); g.drawRect(0, 0, width, height); //4.填充背景 g.setColor(Color.YELLOW); g.fillRect(1, 1, width-1, height-1); //5.画一些干扰线条 g.setColor(Color.GRAY); Random random = new Random(); for(int i=1;i<=20;i++) g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height)); //6.画字符串随机的 g.setColor(Color.RED); //设置字体 g.setFont(new Font("宋体",Font.BOLD|Font.ITALIC,20)); for(int i=1;i<=4;i++) g.drawString(random.nextInt(10)+"", i*20,20); //清除缓存 response.setHeader("Expires", "-1"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); //7.输出 response.setContentType("image/jpeg"); ImageIO.write(img, "jpg", response.getOutputStream()); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); }}
前台页面用Img标签的src属性指定action地址即可显示验证码。
评论前必须登录!
立即登录