我使用以下代码为表单设置不同的提交按钮。问题是,如果我更改每个提交按钮的value属性的值,我也必须更改Java代码,就好像条件是基于这些值一样。
我正在寻找一种替代解决方案来避免这个问题,这样后端和前端就可以独立了。
JSP
<s:form name="myform" method="POST" action="myformActions">
.....
<input id="sub1Btn" type="submit" name="action" value="mysubmit1"/>
<input id="sub2Btn" type="submit" name="action" value="mysubmit2"/>
</s:form>
Java
{
....
private String action;
....
public void myformActions(){
if(action.equalsIgnoreCase("mysubmit1") //if I change the value need to change this as well
{
do whatever is required to fulfill the request of mysubmit1 ...
}
if(action.equalsIgnoreCase("mysubmit2") //if I change the value need to change this as well
{
do whatever is required to fulfill the request of mysubmit2 ...
}
}
}
我没有浏览所有的评论,但从你的问题来看,我有一个想法,你可以使用一些javascript函数来根据你想要的标准设置表单的操作。因此,当提交表单时,将调用相应的操作。您甚至可以使用单个操作类和不同的方法,如编辑、添加等,这些方法可以映射到struts.xml文件中。在这种情况下,映射可以像action="*user" method="{1}"
一样完成,因此操作类中的方法edit()将被调用用于操作editUser,delete()将用于deleteUser。。。
此解决方案可能并非在所有情况下都是好的,并且不会直接回答问题。我的解决方案取决于您操作的基本。如果您的按钮在一个对象上定义了不同的操作,您可以执行以下操作。
这不会把按钮从你的操作中移开,而是把它们放在它们应该放的地方。
考虑一个带有表单的页面,用户可以完成表单并将其提交到结果页面。结果页面将有导出按钮,用户可以将表单保存为html、pdf、excel格式。
您的jsp
<s:submit button="true" key="form.btn.export.pdf" name="export" />
<s:submit button="true" key="form.btn.export.excel" name="export"/>
<s:submit button="true" key="form.btn.export.html" name="export" />
然后在您的操作中,导出setter将是if/else或switch语句(不是简单的setter):
public void setExport(String exportBtn) {
if (exportBtn.toUpperCase().contains("PDF")) {
this.export = "PDF";
} else if (exportBtn.toUpperCase().contains("EXCEL")) {
this.export = "XLSX";
} else if (exportBtn.toUpperCase().contains("CVS")) {
this.export = "CVS";
} else if (exportBtn.toUpperCase().contains("HTML")) {
this.export = "HTML";
}
LOG.debug("Exporting to is " + this.export);
}
那么在你的行动中不需要任何if/else。
@Action(value = "export-action")
public String exportMethod(){
ExportHelper ex= new ExportHelper("report",export);//No if is required
inputStream = new ByteArrayInputStream( ExportHelper);
}
这种简单的解决方案使您的操作更易于维护。
提示。在这个解决方案中,后端和前端没有耦合!我们将前端(jsp)耦合到控制器(StrutsAction)。这是一个不错的方法。
使用submit标记的方法或操作属性将每个属性重定向到不同的方法/操作。