我们正在努力使用一些脏代码来国际化旧应用程序。例如,我们有一个对象 DTO InstrumentDto
:
private String label;
private Quotation quotation;
private ExprQuote quoteExp;
public String getTypeCouponCouru() {
if (this.quoteExp.getCode().equals(Constants.INS_QUOTE_EXPR_PCT_NOMINAL_CPN_INCLUS)
|| this.quoteExp.getCode().equals(Constants.INS_QUOTE_EXPR_PCT_NOMINAL_INTERET)) {
return "Coupon attaché";
} else if(this.quoteExp.getCode().equals(Constants.INS_QUOTE_EXPR_PCT_NOMINAL_PIED_CPN)){
return "Coupon détaché";
} else {
return "";
}
}
public String getFormattedLabel() {
StringBuilder formattedLabel = new StringBuilder(this.label);
Quotation quote = this.quotation;
if (this.quotation != null) {
formattedLabel.append(" ");
formattedLabel.append(FormatUtil.formatDecimal(this.quotation.getCryQuote());
if (this.quoteExp.getType().equals("PERCENT")) {
formattedLabel.append(" %");
} else {
formattedLabel.append(" ");
formattedLabel.append(this.quotation.getCurrency().getCode());
}
formattedLabel.append(" le ");
formattedLabel.append(DateUtil.formatDate(this.quotation.getValoDate()));
}
return formattedLabel.toString();
}
然后,这些方法被用在 JSP 上。例如,对于 getFormattedLabel()
,我们有:
<s:select name = "orderUnitaryForm.fieldInstrument"
id = "fieldInstrument"
list = "orderUnitaryForm.instrumentList"
listKey = "id"
listValue = "formattedLabel" />
IMO,第一种方法在 DTO 中没有自己的位置。我们期望 View 能够管理要打印的标签。并且在这个 View (JSP)中,翻译那些词没有问题。 另外,该方法仅在2个JSP中使用。 “重复”条件测试不是问题。
但是 getFormattedLabel()
比较困难:这种方法在很多 JSP 中使用,并且格式化标签的构建“复杂”。而且 DTO 中不可能有 i18n 服务。
那么如何做到这一点?
最佳答案
您在 getFormattedLabel()
中的代码似乎是业务逻辑。
DTO 是一个简单的对象,没有任何复杂的测试/行为(请参阅 wiki definition )。
IMO,您应该将这段代码移动到您的操作中,并像这样拆分您的 *.properties 文件:
您的*.属性:
message1= {0} % le {1}
message2= {0} {1} le {2}
您的行动:
public MyAction extends ActionSupport {
public String execute(){
//useful code here
InstrumentDto dto = new InstrumentDto();
StringBuilder formattedLabel = new StringBuilder(label);
if (this.quotation != null) {
String cryQuote = FormatUtil.formatDecimal(this.quotation.getCryQuote());
String date = DateUtil.formatDate(this.quotation.getValoDate());
if (this.quoteExp.getType().equals("PERCENT")) {
formattedLabel.append(getText("message1", new String[] { cryQuote, date }));
} else {
String cryCode = this.quotation.getCurrency().getCode();
formattedLabel.append(getText("message2", new String[] { cryQuote, cryCode, date }));
}
}
dto.setFormattedLabel(formattedLabel);
}
}
希望这会有所帮助;)
关于java - 如何在 Struts 2 中转换 DTO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31207357/