ActionMessages errors = new ActionMessages(); 

AuthCodeCookie authCodeCookie = new AuthCodeCookie(request,response);

if (!authCodeCookie.getAuthCode().equals(form.getAuthCode())) {//验证码不正确

errors.add("error.login.authcode", new ActionMessage("error.login.authcode"));//ApplicationResources.properties

this.saveErrors(request, errors);

return mapping.getInputForward();//不跳转,必须在action中指定input属性

}


html中必须有:<html:errors/>接收


登录的时候保存验证码到cookies,详见:验证码的生成,并且“看不清,换一张”

AuthCodeCookie authCodeCookie = new AuthCodeCookie(request, response);

authCodeCookie.addAuthCode(authCode);//保存验证码到cookies


cookies类

public class AuthCodeCookie {

private HttpServletRequest request;

private HttpServletResponse response;

public AuthCodeCookie(HttpServletRequest request,

HttpServletResponse response) {

this.request = request;

this.response = response;

}


public void addAuthCode(String authCode) {

addCookie("AUTHCODE", authCode);

}


public void addCookie(String name, String value) {

Cookie cookies = new Cookie(name, value);

cookies.setPath("/");

cookies.setMaxAge(-1);//设置cookie经过多长秒后被删除。如果0,就说明立即删除。如果是负数就表明当浏览器关闭时自动删除。

response.addCookie(cookies);

}


public String getAuthCode(){

return getCookies("AUTHCODE");

}


public String getCookies(String cookieName) {

Cookie[] cookies = request.getCookies();

Cookie cookie = null;

try {

if (cookies != null && cookies.length > 0) {

for (int i = 0; i < cookies.length; i++) {

cookie = cookies[i];

if (cookie.getName().equals(cookieName)) {

return cookie.getValue();

}

}

}

} catch (Exception e) {

e.printStackTrace();

}

return "";

}

}