Java 如何在Struts 2中转换DTO
我们正在用一些脏代码对一个旧的应用程序进行国际化。例如,我们有一个对象DTOJava 如何在Struts 2中转换DTO,java,jsp,struts2,internationalization,dto,Java,Jsp,Struts2,Internationalization,Dto,我们正在用一些脏代码对一个旧的应用程序进行国际化。例如,我们有一个对象DTOInstrumentDto: private String label; private Quotation quotation; private ExprQuote quoteExp; public String getTypeCouponCouru() { if (this.quoteExp.getCode().equals(Constants.INS_QUOTE_EXPR_PCT_NOMINAL_CPN_
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()
,我们有:
在我看来,第一种方法在DTO中没有一席之地。我们希望视图能够管理要打印的标签。在这个视图(JSP)中,翻译这些单词没有问题。
此外,此方法仅在2JSP中使用。“重复”条件测试不是问题
但是对于getFormattedLabel()
,它更难:这种方法在很多JSP中都使用,并且格式化标签的构建是“复杂的”。在DTO中不可能有i18n服务
那么如何做到这一点呢?您在
getFormattedLabel()
中的代码似乎是业务逻辑
DTO是一个简单的对象,没有任何复杂的测试/行为(请参阅)
在我看来,您应该将这段代码移动到您的操作中,并按如下方式拆分*.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);
}
}
希望这会有所帮助;) 。我觉得这个问题比仅仅使用
text
或getText()
(或者我遗漏了什么?)更复杂。不,这根本不是问题,S2 i18n多年来一直是框架的关键功能。但是使用它需要一些技巧。谢谢你的解决方案。是的,它起作用了。但这是最好的解决方案吗?如果我必须在一个服务中相互化这个逻辑(它没有扩展ActionSupport,因此无法访问getText()),我会被阻止。也许服务中的方法可以返回“message1”或“message2”,这是使用.properties转换它的操作:但是如何注入参数呢?我想用taglib来解决这个问题,但有可能吗?