0

我对Struts2比较陌生。 我已经开始使用ModelDriven来减少开发中的开销。 我想编写一个接口来修改一个属性,但是我没有看到如何访问为模型实现ModelDriven的类的属性。Struts2 - 实现ModelDriven - 创建一个访问模型属性的拦截器

我可以看到像validate()这样的事情可以像在实际操作类中一样工作。 我改变了设计来封装服务背后的逻辑,但仍然想知道这是否可能。

我们正在通过ajax/json做所有事情,所以我发现modeldriven有相当多的帮助 - 不知道是否有更好的替代方案!

编辑 - 代码示例:

试图在一个模板,一个消息来替换消息中的电子邮件正文中使用。

public class EmailActionImpl implements EmailAction { 

private Email email=new Email();  
private EmailService emailService; 

public Email getModel(){ 
    return email; 
} 
[... getters and setters ...] 

    public String execute(){ 
    logger.info("Email action is sendind an email..."); 

    try{ 
     emailService.sendNewMail(email); 
    }catch(Exception e){ 
     logger.error("Email not sent: " + e.getMessage()); 
     return "failure"; 
    } 
    return "success"; 
} 
} 

电子邮件模型是这样的

@Entity 
@Table(name="email") 
public class Email { 
private Long id; 
private String from; 
private String to; 
private String message; 
private String templateType; 
[...] 
} 

我想拦截预处理器,以取代email.message。 应该看起来像这样,但action.getMessage/setMessage不可用。

public class SimpleInterceptor extends AbstractInterceptor { 

public String intercept(ActionInvocation invocation) throws Exception { 
    EmailAction action = (EmailAction)invocation.getAction(); 
    action.setMessage(MessageTemplateFactoryImpl(action.getMessage(), action.getTemplateType()); 
    return invocation.invoke(); 
} 
} 
+0

如果我明白它的权利,你想修改从表单中设置的属性? – 2012-03-22 16:08:42

+0

你究竟想要做什么?不知道这很难说。您可以修改请求中的值,但实现自己的类型转换器通常更有意义。这两种方法都涵盖了很多情况,并避免检查操作并直接使用自己的拦截器设置值。 – Quaternion 2012-03-22 18:46:34

+0

我会尽快发布代码示例。 – JasonG 2012-03-22 18:59:47

回答

0

如果你仍然想实现拦截到一组特定的模型工作,然后你会如果action实现了模型驱动检查。通过反射(或Apache bean utils),您可以派生出相关的特定模型,以确定您的拦截器是否适用,然后相应地对其执行操作。

+0

伟大 - 真实 - 反思。刚才昨天学到了这个概念。这将是一个有趣的实验。 – JasonG 2012-03-27 12:00:26