Struts2中ModelDriven的陷阱及其预防

页面表单

<form action="updateInput.action" method="post">
<input type="text" name="id"/>
<input type="submit" value="查询">
</form>

struts.xml配置

<action name="updateInput" class="com.test.UserAction" method="updateInput">
<result name="update_input">user_update.jsp</result>
</action>

com.test.UserAction

public class UserAction implements ModelDriven {

    private User user;

    @Override
public Object getModel() {
if (user == null) {
user = new User();
}
return user;
} public String updateInput() {
//测试ModelDriven陷阱
// 根据ID,查询数据库,得到User对象
Object object = ActionContext.getContext().getValueStack().findValue("#root");
Connection connection = DBConnection.getConnection();
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
User user1 = null;
try {
System.out.println("查询用户信息");
preparedStatement = connection
.prepareStatement("select * from t_user where id = ?");
preparedStatement.setInt(1, user.getId());
resultSet = preparedStatement.executeQuery(); if (resultSet.next()) {
user1 = new User();
user1.setId(resultSet.getInt("id"));
user1.setUsername(resultSet.getString("username"));
user1.setPassword(resultSet.getString("password"));
// user = user1;//这样写有问题
//值栈中的user并没有引用user1,所以在页面上取值实际上并没有取到user1的值。
//将user1的属性copy到user中之后,就可以在页面上取到值了。
BeanUtils.copyProperties(user, user1);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
DBConnection.close(resultSet, preparedStatement, connection);
}
return "update_input";
}
}

user_update.jsp

<form action="user_update.action" method="post">
<input type="hidden" name="method:update">
id:<input type="text" name="id" value="<s:property value="id"/>"> <br/>
username:<input type="text" name="username" value="<s:property value="username"/>"> <br/>
password:<input type="text" name="password" value="<s:property value="password"/>"> <br/>
<input type="submit" name="submit" value="更新用户">
</form>
上一篇:Js创建对象的做法


下一篇:《java.util.concurrent 包源码阅读》20 DelayQueue