纵有疾风起
人生不言弃

Struts2自定义结果视图(servlet验证码)

1、编写一个类实现com.opensymphony.xwork2.Result,或者继承org.apache.struts2.dispatcher.StrutsResultSupport

Struts2自定义结果视图(servlet验证码)插图

 

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地址即可显示验证码。

 

文章转载于:https://www.cnblogs.com/lm970585581/p/8675872.html

原著是一个有趣的人,若有侵权,请通知删除

未经允许不得转载:起风网 » Struts2自定义结果视图(servlet验证码)

分享到: 生成海报
avatar

评论 抢沙发

评论前必须登录!

立即登录   注册

切换注册

登录

忘记密码 ?

切换登录

注册

我们将发送一封验证邮件至你的邮箱, 请正确填写以完成账号注册和激活