zoukankan      html  css  js  c++  java
  • 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>


  • 相关阅读:
    VS2017专业版和企业版激活密钥
    RabbitMQ卸载重新安装
    RabbitMQ-基本命令操作
    天猫
    铜氨纤维
    四肢很发达,头脑不简单
    运动可以健身健脑
    1 职业天花板来自认识的局限性
    天猫-服饰行业标准
    服装设计都是需要什么
  • 原文地址:https://www.cnblogs.com/umgsai/p/3908072.html
Copyright © 2011-2022 走看看