我们希望避免在基于 struts 2 Web 的应用程序中通过 Ajax 发送多请求。
可s:token
用于常规请求-响应 jsp 页面,但不适用于 ajax 请求。
这是样本
该应用程序具有使用 ajax post 方法验证字段的表单(我使用的是 struts jquery 插件,并且 jQuery post 是动态生成的)。
<s:form id="formValidateCustom" action="login">
<s:token/>
<s:textfield name="login" />
<span id="loginError">
<sj:submit button="true" validateFunction="customeValidation" />
</s:form>
登录动作如下:
@InterceptorRef("jsonValidationWorkflowStack")
@Validations(requiredStrings = {
@RequiredStringValidator(fieldName = "loginuser", type = ValidatorType.FIELD, message = "Login User is required")
})
public class Login extends ActionSupport {
@Action(value = "/login", results = {
@Result(location = "simpleecho.jsp", name = "success")
})
public String execute() throws Exception
{
echo = "Welcome " + login;
log.info(echo);
return SUCCESS;
}
}
有一个用于处理错误的自定义 js。这个函数在 Ajax 调用结束时被调用。它读取所有错误并搜索命名field'Error'
并添加错误文本的 html 字段:
function customeValidation(form, errors) {
if (errors.fieldErrors) {
$.each(errors.fieldErrors, function(index, value) {
var elem = $('#'+index+'Error');
if(elem)
{
elem.html(value[0]);
}
});
}
}
完整的示例位于http://struts.jgeppert.com/struts2-jquery-showcase/index.action。请转到Ajax>Form>Form with Custom Validation
当用户将登录字段留空时,ajax 请求会返回错误,但表单中的令牌不会用新令牌更新。这是因为没有再次执行,因为只进行了一个ajax调用,并且jsp没有完全加载。
我仍然可以使用提供的解决方案Unable to implementation Struts 2 token interceptor with hyperlink。在我必须s:token
通过 jQuery 手动将隐藏字段更新为新令牌
有没有更好的办法!
我在HOWTO do CSRF protection in Struts2 application for AJAX requests 中发现了这个问题,但我想知道是否有更好的方法?(我认为这是一个非常普遍的问题,必须在 struts 中进行管理)