struts2 验证码 收集
WEB-INF/applicationContext.xml
Java代码
<?xml version="1.0" encoding="UTF-8"?>??
<beans xmlns="http://www.springframework.org/schema/beans"??
??? xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"??
??? xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">??
?
<bean id="dataSource" name="dataSource" destroy-method="close">??
??? <property name="driverClass" value="com.mysql.jdbc.Driver" />??
??? <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/db?useUnicode=true&characterEncoding=UTF-8"/>??
??? <property name="user" value="root" />??
??? <property name="password" value="root" />??
??? <property name="maxPoolSize" value="50" />??
??? <property name="minPoolSize" value="1" />??
??? <property name="initialPoolSize" value="1" />??
??? <property name="maxStatements" value="0"/>????
??? <property name="maxIdleTime" value="20" />??
</bean>??
?
<bean id="sessionFactory" name="sessionFactory" ref="dataSource" />??
??? <property name="mappingResources">??
??????? <list>??
??????????? <value>model/User.hbm.xml</value>??
??????? </list>??
??? </property>??
??? <property name="hibernateProperties">??
??????? <props>??
??????????? <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>??
??????????? <prop key="hibernate.show_sql">true</prop>??
??????????? <prop key="hibernate.use_sql_comments">false</prop>??
??????????? <prop key="hibernate.hbm2ddl.auto">update</prop>??
??????????? <prop key="hibernate.jdbc.batch_size">20</prop>??
??????? </props>??
??? </property>??
</bean>??
?
<bean id="transactionManager" name="transactionManager" ref="sessionFactory" />??
</bean>??
?
<bean id="transactionInterceptor" name="transactionInterceptor" ref="transactionManager" />??
??? <property name="transactionAttributes">??
??????? <props>??
??????????? <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>??
??????????? <prop key="*">PROPAGATION_REQUIRED</prop>??
??????? </props>??
??? </property>??
</bean>??
?
<bean id="BeanNameAutoProxyCreator" name="BeanNameAutoProxyCreator" name="mgr" ref="userDAO" />??
</bean>??
?
<bean id="userDAO" name="userDAO" ref="sessionFactory" />??
</bean>??
?
</beans>?
WEB-INF/web.xml
Java代码
<?xml version="1.0" encoding="UTF-8"?>??
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"??
??? xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"??
??? xsi:schemaLocation="http://java.sun.com/xml/ns/javaee???
??? http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">??
??????
??? <context-param>????
???? <param-name>contextConfigLocation</param-name>????
???? <param-value>/WEB-INF/applicationContext.xml</param-value>????
??? </context-param>????
??? <!-- 用于初始化Spring容器的Listener -->??
??? <listener>??
??????? <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>??
??? </listener>??
??????
??? <filter>??
??????? <filter-name>encodingFilter</filter-name>??
??????? <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>??
??????? <init-param>??
??????????? <param-name>encoding</param-name>??
??????????? <param-value>UTF-8</param-value>??
??????? </init-param>??
??????? <init-param>??
??????????? <param-name>forceEncoding</param-name>??
??????????? <param-value>true </param-value>??
??????? </init-param>??
??? </filter>??
??? <filter-mapping>??
??????? <filter-name>encodingFilter</filter-name>??
??????? <url-pattern>/*</url-pattern>??
??? </filter-mapping>??
??????
??? <filter>??
??????? <filter-name>openSessionInViewFilter</filter-name>??
??????? <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>??
??? </filter>??
??? <filter-mapping>??
??????? <filter-name>openSessionInViewFilter</filter-name>??
??????? <url-pattern>/*</url-pattern>??
??? </filter-mapping>??
?
??? <filter>??
??????? <filter-name>struts-cleanup</filter-name>??
??????? <filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>??
??? </filter>??
??? <filter-mapping>??
??????? <filter-name>struts-cleanup</filter-name>??
??????? <url-pattern>/*</url-pattern>??
??? </filter-mapping>??
??????
??? <filter>??
??????? <filter-name>struts2</filter-name>??
??????? <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>??
??? </filter>??
??? <filter-mapping>??
??????? <filter-name>struts2</filter-name>??
??????? <url-pattern>/*</url-pattern>??
??? </filter-mapping>??
</web-app>??
model.User.java
Java代码
package model;??
?
public class User??
{??
??? private int Id;??
??? private String username;??
??? private String password;??
??????
??? public int getId()??
??? {??
??????? return Id;??
??? }??
??? public void setId(int id)??
??? {??
??????? Id = id;??
??? }??
??? public String getUsername()??
??? {??
??????? return username;??
??? }??
??? public void setUsername(String username)??
??? {??
??????? this.username = username;??
??? }??
??? public String getPassword()??
??? {??
??????? return password;??
??? }??
??? public void setPassword(String password)??
??? {??
??????? this.password = password;??
??? }??
}?
model/User.hdm.xml
Java代码
<?xml version="1.0" encoding="UTF-8"?>??
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"??
?????????????????????????????????? "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">??
<hibernate-mapping default-access="field" package="model">??
??? <class name="User" table="admin">??
??????? <id name="Id" column="Id">??
??????????? <generator />??
??????? </id>??
??????? <property name="username" column="username" not-null="true" generated="never" lazy="false" unique="true"/>??
??????? <property name="password" column="password" not-null="true" generated="never" lazy="false" />??
??? </class>??
</hibernate-mapping>??
login.jsp
Java代码
<%@ page language="java" import="java.util.*"??
??? contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>??
<%@taglib prefix="s" uri="/struts-tags"%>??
<%@taglib prefix="sx" uri="/struts-dojo-tags"%>??
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">??
<script type="text/javascript">??
??? function refresh()??
??? {??
??????? document.getElementById("authImg").src = "authImg?d=" + new Date().getTime();??
??? }??
</script>???
<html>??
??? <head>??
??????? <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">??
??????? <sx:head/>???
??????? <title><s:text name="%{getText('loginPage')}" /></title>??
??? </head>??
??? <body>??
??????? <div style="color: red">??
??????????? <s:actionerror/>??
??????? </div>??
??????? <s:form action="Login" method="post" name="form" onsubmit="return validate(document.form)">??
??????????? <s:textfield label="%{getText('username')}" name="username" value="" cssStyle="width:150px;" />??
??????????? <s:password label="%{getText('password')}" name="password" value="" cssStyle="width:150px;" />??
??????????? <s:textfield label="%{getText('vercode')}" name="vercode" value="" cssStyle="width:150px;" />??
??????????? <s:submit value="%{getText('login')}"/>??
??????? </s:form>??
??????? 验证码如图:<img src="authImg" id="authImg"/>看不清?<a href="#" onClick="refresh()">单击此处刷新</a>??
??? </body>??
</html>?
action.LoginAction.java
Java代码
package action;??
?
import java.util.Map;??
import javax.servlet.http.HttpServletResponse;??
import org.apache.struts2.ServletActionContext;??
import com.opensymphony.xwork2.ActionContext;??
?
public class LoginAction extends BaseAction??
{??
??? private static final long serialVersionUID = 1L;??
??????
??? public String getUsername()??
??? {??
??????? return username;??
??? }??
??? public void setUsername(String username)??
??? {??
??????? this.username = username;??
??? }??
??? public String getPassword()??
??? {??
??????? return password;??
??? }??
??? public void setPassword(String password)??
??? {??
??????? this.password = password;??
??? }??
??? public String getVercode()??
??? {??
??????? return vercode;??
??? }??
??? public void setVercode(String vercode)??
??? {??
??????? this.vercode = vercode;??
??? }??
??????
??? @SuppressWarnings("unchecked")??
??? public String execute() throws Exception??
??? {??
??????? Map session = ActionContext.getContext().getSession();??
??????? String ver = (String)session.get("authImg");??
?
??????? if (ver.equals(vercode))??
??????? {??
??????????? int userId = mgr.loginValid(username,password);??
????
??????????? if (userId > 0)??
??????????? {??
??????????????? return SUCCESS;??
??????????? }??
??????????? else??
??????????? {??
??????????????? addActionError(getText("noMatch"));??
??????????? }??
??????? }??
??????? else??
??????? {??
??????????? System.out.println("0k3");??
??????????? addActionError(getText("vercodeErr"));??
??????? }??
??????? return "failure";??
??? }??
?
??? private String username;??
??? private String password;??
??? private String vercode;??
}??
UserDAOHibernate.java
Java代码
package dao.user;??
?
import java.util.List;??
import org.springframework.dao.DataAccessException;??
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;??
import model.User;??
?
public class UserDAOHibernate extends HibernateDaoSupport implements UserDAO??
{??
??? @SuppressWarnings("unchecked")??
??? public User findUserByNameAndPass(String username , String password)??
??? {??
??????? List ul = null;??
??????? try??
??????? {??
???????????? [color=red]ul = getHibernateTemplate().find("from User au where au.username = ? and au.password = ?" ,new String[]{username,password});[/color]??
??????? } catch(DataAccessException e)??
??????? {??
??????????? System.out.println("数据访问异常");??
??????????? e.printStackTrace();??
??????? }??
?????????
??????? System.out.println(ul.size());??
??????? if (ul != null && ul.size() >= 1)??
??????? {??
??????????? return (User)ul.get(0);??
??????? }??
??????? return null;??
??? }??
?
??? @SuppressWarnings("unchecked")??
??? public User findUserByName(String username)??
??? {??
????? [color=red]? List ul = getHibernateTemplate().find("from User au where au.username = ?" ,username);[/color]??
??????? if (ul != null && ul.size() >= 1)??
??????? {??
??????????? return (User)ul.get(0);??
??????? }??
??????? return null;??
??? }??
?
??? @Override??
??? public User get(int id)??
??? {??
??????? return (User)getHibernateTemplate().get(User.class, id);??
??? }??
}??
问题描述,1.验证码不显示,2.但是后台能发现6位验证码,当正确的用户名,密码,和后台的验证码后,jsp页面出现:
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
java.lang.reflect.InvocationTargetException
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:440)
com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:279)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:163)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:249)
org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:148)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:93)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:128)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.interceptor.ProfilingActivationInterceptor.intercept(ProfilingActivationInterceptor.java:104)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:148)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:128)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:468)
org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395)
org.apache.struts2.dispatcher.ActionContextCleanUp.doFilter(ActionContextCleanUp.java:102)
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:174)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:96)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
控制台出现:
12:16:11,779 DEBUG SessionImpl:248 - opened session at timestamp: 12527289717
12:16:12,193 DEBUG JDBCTransaction:82 - begin
12:16:12,194 DEBUG ConnectionManager:444 - opening JDBC connection
12:16:12,197 DEBUG JDBCTransaction:87 - current autocommit status: true
12:16:12,200 DEBUG JDBCTransaction:90 - disabling autocommit
12:16:12,469 DEBUG JDBCTransaction:186 - rollback
12:16:12,471 DEBUG JDBCTransaction:227 - re-enabling autocommit
12:16:12,475 DEBUG JDBCTransaction:197 - rolled back JDBC Connection
12:16:12,476 DEBUG ConnectionManager:325 - transaction completed on session with on_close connection release mode; be sure to close the session to release JDBC resources!
12:16:12,480 DEBUG ConnectionManager:464 - releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)]
12:16:12,480 DEBUG ConnectionManager:325 - transaction completed on session with on_close connection release mode; be sure to close the session to release JDBC resources!
非常感谢大家。。。。。
问题补充:
liyaxi
现在异常没了,但是还是无法显示验证码图片
我的所有action都是默认命名空间,并且没有重命名的action
另外我生成图片的类是:
Java代码
package authImg;??
?
import java.io.*;??
import java.awt.*;??
import java.awt.image.*;??
import java.util.*;??
import javax.imageio.*;??
import javax.imageio.stream.ImageOutputStream;??
?
public class AuthImg???
{??
??? private static final long serialVersionUID = 1L;??
??? //设置图形验证码中字符串的字体和大小??
??????
??? private ByteArrayInputStream image;//图像?????
??? private String str;//验证码?????
?????????
??? public AuthImg()??
??? {?????
??????? init();??
??? }?????
??? /*???
???? * 取得AuthImg实例???
???? */????
??? public static AuthImg Instance(){?????
??????? return new AuthImg();?????
??? }?????
??? /*???
???? * 取得验证码图片???
???? */????
??? public ByteArrayInputStream getImage()??
??? {?????
??????? return this.image;?????
??? }?????
??? /*???
???? * 取得图片的验证码???
???? */????
??? public String getString()??
??? {?????
??????? return this.str;?????
??? }?????
??????????
??? /*?
???? * 生成随机颜色?
???? */??
??? private Color getRandColor(int fc, int bc)??
??? {??
??????? Random random = new Random();??
??????? if (fc > 255)??
??????????? fc = 255;??
??????? if (bc > 255)??
??????????? bc = 255;??
??????? int r = fc + random.nextInt(bc - fc);??
??????? int g = fc + random.nextInt(bc - fc);??
??????? int b = fc + random.nextInt(bc - fc);??
??????? return new Color(r, g, b);??
??? }??
??? /*?
???? * 生成服务器响应的服务方法?
???? */??
??? public void init()??
??? {??
??????? int width = 100, height = 18;??
??????? //生成一张新图片??
??????? BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);??
??????? //在图片中绘制内容??
??????? Graphics g = image.getGraphics();??
??????? Random random = new Random();??
??????? g.setColor(getRandColor(200, 250));??
??????? g.fillRect(1, 1, width - 1, height - 1);??
??????? //设定背景色?????
??????? g.setColor(new Color(102, 102, 102));??
??????? g.drawRect(0, 0, width - 1, height - 1);??
??????? g.setFont(new Font("Arial Black", Font.PLAIN, 16));??
??????? //随机生成线条,让图片看起来更加杂乱??
??????? g.setColor(getRandColor(160, 200));??
??????? for (int i = 0; i < 155; i++)??
??????? {??
??????????? int x = random.nextInt(width - 1);??
??????????? int y = random.nextInt(height - 1);??
??????????? int xl = random.nextInt(6) + 1;??
??????????? int yl = random.nextInt(12) + 1;??
??????????? g.drawLine(x, y, x + xl, y + yl);??
??????? }??
??????? for (int i = 0; i < 70; i++)??
??????? {??
??????????? int x = random.nextInt(width - 1);??
??????????? int y = random.nextInt(height - 1);??
??????????? int xl = random.nextInt(12) + 1;??
??????????? int yl = random.nextInt(6) + 1;??
??????????? g.drawLine(x, y, x - xl, y - yl);??
??????? }??
??????? //用于保存系统生成的随机字符串??
??????? StringBuffer sRand = new StringBuffer(6);??
??????? for (int i = 0; i < 6; i++)??
??????? {??
??????????? String tmp = getRandomChar();??
??????????? sRand = sRand.append(tmp);??
??????????? //将系统生成的随机字符添加到图形验证码图片上??
??????????? g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));??
??????????? g.drawString(tmp, 15 * i + 10, 15);??
??????? }??
??????? //赋值验证码??
??????? this.str = sRand.toString();???
?
??????? g.dispose();?????
??????? ByteArrayInputStream input = null;?????
??????? ByteArrayOutputStream output = new ByteArrayOutputStream();?????
??????? //输出图形验证码图片??
??????? try??
??????? {?????
??????????? ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);?????
??????????? ImageIO.write(image, "bmp", imageOut);?????
??????????? imageOut.close();?????
??????????? input = new ByteArrayInputStream(output.toByteArray());?????
??????? }catch(Exception e){?????
??????????? System.out.println("验证码图片产生出现错误:" + e.toString());?????
??????? }????
??????? //赋值图像????
??????? this.image = input;?????
??? }??
??? /*?
???? * 生成随机字符?
???? */??
??? private String getRandomChar()??
??? {??
??????? int rand = (int) Math.round(Math.random() * 2);??
??????? long itmp = 0;??
??????? char ctmp = '\u0000';??
??????? switch(rand)??
??????? {??
??????? //生成大写字母的情形??
??????? case 1:??
??????????? itmp = Math.round(Math.random() * 25 + 65);??
??????????? ctmp = (char) itmp;??
??????????? return String.valueOf(ctmp);??
??????? //生成小写字母的情形??
??????? case 2:??
??????????? itmp = Math.round(Math.random() * 25 + 97);??
??????????? ctmp = (char) itmp;??
??????????? return String.valueOf(ctmp);??
??????? //生成数字的情形??
??????? default:??
??????????? itmp = Math.round(Math.random() * 9);??
??????????? return String.valueOf(itmp);??
??????? }??
??? }??
}??
产生图片的action是
Java代码
package action;??
?
import java.io.ByteArrayInputStream;??
import javax.servlet.http.HttpServletResponse;??
import org.apache.struts2.ServletActionContext;??
import authImg.AuthImg;??
import com.opensymphony.xwork2.ActionContext;??
import com.opensymphony.xwork2.ActionSupport;??
?
public class CreateCodeImgAction extends ActionSupport??
{??
??? private static final long serialVersionUID = 1L;??
??????
??? public void setInputStream(ByteArrayInputStream inputStream)??
??? {??
??????? this.inputStream = inputStream;??
??? }??
?
??? public ByteArrayInputStream getInputStream()??
??? {??
??????? return inputStream;??
??? }??
?
??? public String execute() throws Exception??
??? {??
??????? HttpServletResponse response = ServletActionContext.getResponse();??
??????? //阻止生成页面被缓存,保证每次重新生成随机验证码??
??????? response.setHeader("Pragma", "No-cache");??
??????? response.setHeader("Cache-Control", "no-cache");??
??????? response.setHeader("Cache-Control", "no-store");??
??????? response.setDateHeader("Expires", 0);??
??????? response.setContentType("image/jpeg");??
??????????
??????? AuthImg authImg = AuthImg.Instance();??
??????? // 取得带有随机字符串的图片??
??????? setInputStream(authImg.getImage());??
??????? // 取得随机字符串放入HttpSession??
?
??????? System.out.println(authImg.getString());??
??????????
??????? ActionContext.getContext().getSession().put("authImg", authImg.getString());??
??????????
??????? return SUCCESS;??
??? }??
?
??? private ByteArrayInputStream inputStream;??
}?
struts.xml片段
Java代码
<package name="non-authority" extends="struts-default">?????
??????? <action name="Login" class="action.CreateCodeImgAction">??????
?????????? <result type="stream">??????
??????????????? <param name="contentType">image/bmp</param>??????
??????????????? <param name="inputName">inputStream</param>?
??????????? </result>???
????????? <result name="success">login.jsp</result>
?????? </action>?
把这个<result name="success">login.jsp</result> 删除掉就可以了,
最好把, image/bmp 改为? image/jpeg
把这个也改了 ImageIO.write(image, "bmp", imageOut);? ---?? ImageIO.write(image, "jpeg", imageOut);
其实 是人最难发现自己的代码错误的。?? 你的思路很好, 我已经在我的机子上测试了,
没问题。 我以前只用下边的。
Xml代码
<result type="stream">?????????
??????????????? <param name="contentType">image/peg</param>?????????
??????????????? <param name="inputName">inputStream</param>????
??????????? </result>????
?? 做下载用。 楼住举一反三 ,触类旁通。 在咱们论坛里有这篇文章 , 题目:struts2下实现了图片验证码,[url]?? http://tmq.iteye.com/blog/286022 [/url] , 希望对你有帮助。