假设以下操作类可以处理文件上载。
@Namespace("/admin_side")
@ResultPath("/WEB-INF/content")
@ParentPackage(value="struts-default")
public final class CategoryAction extends ActionSupport implements Serializable, ValidationAware, ModelDriven<Category>
{
private static final long serialVersionUID = 1L;
private File fileUpload;
private String fileUploadContentType;
private String fileUploadFileName;
private Long editId;
//Getters and setters.
@Validations(
requiredFields={
@RequiredFieldValidator(fieldName="fileUpload", type= ValidatorType.FIELD, message="Uploading an image is mandatory.")})
@Action(value = "AddCategory",
results = {
@Result(name=ActionSupport.SUCCESS, type="redirectAction", params={"namespace", "/admin_side", "actionName", "Category", "currentPage", "${currentPage}", "message", "${message}", "editId", "${editId}", "status", "${status}"}),
@Result(name = ActionSupport.INPUT, location = "Category.jsp")},
interceptorRefs={
@InterceptorRef(value="defaultStack", params={"params.acceptParamNames", "editId, fileUpload, fileUploadContentType, fileUploadFileName, catId, catName, visible, latest, currentPage, rowCount, totalPages, status", "validation.validateAnnotatedMethodOnly", "true"})
})
public String insertOrUpdate(){
//Do either insert or update based on editId.
return ActionSupport.SUCCESS;
}
@Action(value = "Category",
results = {
@Result(name=ActionSupport.SUCCESS, location="Category.jsp"),
@Result(name = ActionSupport.INPUT, location = "Category.jsp")},
interceptorRefs={
@InterceptorRef(value="defaultStack", params={"params.acceptParamNames", "id, currentPage, rowCount, totalPages, message, status", "validation.validateAnnotatedMethodOnly", "true", "validation.excludeMethods", "load"})})
public String load() throws Exception{
//This method is just required to return an initial view on page load.
return ActionSupport.SUCCESS;
}
}
我想仅在fileUpload
为editId
时验证null
(必填)。如果它初始化为Long
值,则不应执行和排除此验证。在编辑HTML表持有的行时,editId
作为查询字符串参数提供。
有没有办法实现这个目标?
答案 0 :(得分:0)
在我们需要进行此类验证的问题中,我无法准确提及。实际上,我想在动作类中验证java.io.File
字段。
在数据库中插入一行(有一个常用的提交按钮,<s:submit>
用于插入和更新操作),此文件(实际上是一个图像文件)是必需的,但在编辑/更新行时,上传图像是完全可选的。它可能会也可能不会通过文件浏览上传。因此,在更新行时,不应执行此验证(仅当文件要上载时,才会执行其他类型的验证,如文件大小,无效文件类型)。
为了克服这种情况,我跟@FieldExpressionValidator
如下。
@Validations(
fieldExpressions={
@FieldExpressionValidator(fieldName="fileUpload", expression="editId!=null&&fileUpload==null||editId!=null&&fileUpload!=null||editId==null&&fileUpload!=null", key="file.upload.mandatory")
})
这会在插入行时强制显示图像,但在更新行时会使图像成为可选图像。
如果还有更好的选择,那么请添加它们作为答案(我可能错了)。