如何将结果与在Struts 2中返回对象的操作的return语句进行匹配?

时间:2014-03-14 07:39:08

标签: java jsp struts2

我有一个动作searchUser,为此我创建了一个方法getUserById,它返回搜索到的对象。

    public Employee getUserById(int userId) {

    try {
        PreparedStatement preparedStatement = connection.
                prepareStatement("select * from employee where first=? OR last=?");
        preparedStatement.setString(1, employee.getFirstName());
        preparedStatement.setString(2, employee.getLastName());
        ResultSet rs = preparedStatement.executeQuery();

        if (rs.next()) {
            employee.setId(rs.getInt("id"));
            employee.setAge(rs.getInt("age"));
            employee.setFirstName(rs.getString("first"));
            employee.setLastName(rs.getString("last"));
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }

    return employee;
}

现在,struts.xml中的结果匹配项应该是什么 因为通常我们匹配成功字符串。但是知道我怎么能匹配一个物体。日Thnx

2 个答案:

答案 0 :(得分:0)

尝试描述here的ModelDriven设计。基本上,您仍然会从String返回execute,但您还会介绍另一种获取对象的方法:

public class ModelDrivenAction implements ModelDriven { 
    public String execute() throws Exception {
        return SUCCESS;
    }

    public Object getModel() {
        return new Gangster();
    }
}

答案 1 :(得分:0)

  1. Action方法总是返回一个String,如SUCCESS,ERROR,INPUT,NONE等......;
  2. 你不是一个Action方法,它是一个标准方法,因此它不需要在struts.xml文件中映射;
  3. 那就是说,目前还不清楚你想要实现什么:标准的方法是使用私有的Employee对象,Getter和Setter,并从Action方法中填充它(让我们这样做)比如,execute()),然后通过名称从JSP访问它;当来自POST / GET或来自重定向时,userId参数本身应该是具有Getter和Setter的私有变量。

    如果您直接从JSP标记调用它,只需使用它。

    请注意,有多种方法可以避免多次加载,例如将其推到堆栈顶部:

    <s:push value="getUserById(1337)">
        <s:propery value="firstName" />
        <s:propery value="lastName" />
    </s:push>
    

    BTW我 强烈 建议在使用框架之前阅读文档/教程/示例。大多数事情已经存在,开箱即用,等待被发现并正确使用。