我有一个由 BalusC 提供的抽象表单类,用于设置验证消息
public abstract class Form {
// Properties
private Map messages = new LinkedHashMap();
private List formFeedback = new ArrayList();
private List errorMessages = new ArrayList();
private boolean hasError;
然后我有一堆扩展 Form 的类
public class ParentForm extends Form {
public class SubForm1 extends Form {
public class SubForm2 extends Form {
public class SubForm3 extends Form {
在父表单中,我调用每个子表单,但我不知道如何将验证消息从子表单传递到父表单。
public class ParentForm extends Form {
public Object update(HttpServletRequest request) {
pseudo code
//if subform1 is being edited
SubForm1 subForm1 = new SubForm1 (authenticatedUser);
subFormBean1 sfb1 = new subFormBean1 ();
sfb1 = subForm1.update(request);
//if subform2 is being edited
SubForm2 subForm2 = new SubForm2 (authenticatedUser);
subFormBean2 sfb2 = new subFormBean2 ();
sfb2 = subForm2.update(request);
家长Form
服务使用 Struts 风格的 Action 在 servlet 中执行
类UpdateAction
public class UpdateAction implements ControllerAction {
private Form form;
private Object obj;
private HashMap modelMap;
public UpdateAction(HashMap modelMap, Form form, Object obj) {
this.form = form;
this.obj = obj;
this.modelMap = modelMap;
}
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
obj = form.update(request);
request.setAttribute("obj", obj);
request.setAttribute("form", form);
在我的jsps中我会放入
<span class="formError"><c:out value="${form.messages.whatever}" />
但这仅从父表单中获取消息,而不是从任何子表单中获取消息
我想知道是否有类似的事情 `form[subForm].messages.whatever 会起作用吗?类似的东西
if (!sfb1.notSuccess) {
parentForm.setSubFormMessages(sfb1.getMessages());
}
我的项目有点长,但基本上我希望 HTML 页面上的部分(组件??)成为仅在某些条件下才处于 Activity 状态的 HTML 表单(它是我们用于路由的 list 的工作流程应用程序)手动办公)想知道是否最好将其吸收并移植到 JSF 或修改 Form 类。
编辑 我正在尝试实现抽象子表单,但现在子表单上类似的东西仍然会更新 Dao,即使我的条目验证(processEntry)失败
processEntry(request, ad);
processEdit_date(request, ad);
if (isSucces()) {
dao.update(ad, authenticatedUser);
}
最佳答案
您基本上应该在子表单的构造过程中传递ParentForm
。
SubForm1 subForm1 = new SubForm1(this, authenticatedUser);
与
public SubForm1(Form parent, User authenticatedUser) {
this.parent = parent;
this.authenticatedUser = authenticatedUser;
}
然后在 SubForm1
中将消息委托(delegate)给它
public addMessage(field, message) {
parent.addMessage(field, message);
}
为了保持 SubForm1
、SubForm2
等 DRY,您可以按照包装器模式创建另一个抽象类:
public abstract class SubForm extends Form {
private Form parent;
public SubForm(Form parent) {
this.parent = parent;
}
public addMessage(field, message) {
parent.addMessage(field, message);
}
// ...
}
然后设计SubForm1
、SubForm2
等,如下:
public class SubForm1 extends SubForm {
public SubForm1(Form parent, User authenticatedUser) {
super(parent);
this.authenticatedUser = authenticatedUser;
}
// ...
}
关于java - 在单个 View 上显示多个表单时的表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12394298/