1.工程文件夹如下:
2. HelloAction.java代码如下。StrutsResultSupport是struts的自定义结果集。我们的HelloAction类只要继承StrutsResultSupport抽象类并实现doExecute方法,就可以把doExecute方法里面的验证码图片code传到调用这个HelloAction类的jsp页面啦~~ 下面是用get和set注入的方法从struts.xml里面为验证码图片的高和宽赋值。
package com.itheima.web.action;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.StrutsResultSupport;
import cn.dsna.util.images.ValidateCode;
import com.opensymphony.xwork2.ActionInvocation;
public class HelloAction extends StrutsResultSupport{
private int width;
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
private int height;
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
@Override
protected void doExecute(String arg0, ActionInvocation arg1)
throws Exception {
ValidateCode code = new ValidateCode(240,40,4,10);
HttpServletResponse respone = ServletActionContext.getResponse();
code.write(respone.getOutputStream());
}
}
3.struts.xml代码如下。<package name="p2" extends="struts-default" abstract="true"> abstract用来定义包为抽象的,也就是不能包含Action的定义,但是抽象包可以被其他包继承,因此里面可以定义其他包需要的元素,比如ResultType、Interceptor等等。比如下面p2包继承了struts-default抽象包,它定义为抽象包。就可以 引用自定义返回结果类型的<result-type>标签了。
<?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"> <!-- 照抄的,dtd说明了才能用struts标签 -->
<struts>
<constant name="struts.action.extension" value="do" ></constant>
<constant name="struts.configuration.xml.reload" value="true"></constant> <!--每次不用重启 -->
<constant name="struts.enable.DynamicMethodInvocation" value="true"></constant> <!-- 允许动态调用 -->
<package name="p2" extends="struts-default" abstract="true">
<result-types>
<result-type name="myValidate" class="com.itheima.web.action.HelloAction">
</result-type>
</result-types>
<!-- 全局视图:前后端都可以识别的参数 -->
<global-results>
<result name="success" type="myValidate">
<param name="width">200</param>
<param name="height">60</param>
</result>
</global-results>
</package>
<package name="p3" extends="p2" >
<action name="valicoderTest"></action>
</package>
</struts>
4.jsp页面。<img src="valicoderTest.do" />直接输出验证码图片。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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">
<title>Insert title here</title>
</head>
<body>
<form action="" method="post">
用户名:<input type="text" name="username"><br><br>
密码:<input type="password" name="pwk"><br>
注册码:<input type="text" name="username"><img src="valicoderTest.do" /><br>
<input type="submit" value="注册"><br>
</form>
</body>
</html>
结果: