我们正致力于使用一些脏代码来使旧应用程序国际化。例如,我们有一个对象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上没有它的位置。我们期望视图管理要打印的标签。在这个视图(JSP)中,翻译这些单词没有问题。 此外,此方法仅用于2 JSP。没问题&#34;重复&#34;条件测试。
但getFormattedLabel()
更难:这个方法在很多JSP中使用,格式化标签的构建是“复杂的”#34;。并且不可能在DTO中使用i18n服务。
那怎么做?
答案 0 :(得分:2)
getFormattedLabel()
中的代码似乎是业务逻辑。
DTO是一个简单的对象,没有任何复杂的测试/行为(参见wiki definition)。
IMO,您应该将这段代码移动到您的Action并将您的* .properties文件拆分为:
你的* .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);
}
}
希望这会有所帮助;)