我有一个包含字段的表单,我将更改用户值。 但我没有指定值密码字段。 例如,我更改了一些值并提交但未更改密码字段。
<form action="/User" method="get">
<input type="hidden" name="id" value="${param.id}" />
<input type="hidden" name="command" value="editUser"/>
Full name: <input type="text" name="fullName" value="${param.fullName}"/><br/>
Password: <input type="text" name="password"><br/>
name="role"/><br/>
<input type="submit" value="Add"/>
</form>
因此,servlet在password变量中收到一个空值,并在UserDao中传递值。 我需要,如果密码更改,必须在数据库中更改, 否则不会改变。
public void updateUser(User user){
Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("update \"User\" set id_role = ?, fullname = ?, password = ? WHERE id = ?");
preparedStatement.setInt(1, user.getIdRole());
preparedStatement.setString(2, user.getFullName());
preparedStatement.setString(3, user.getPassword()!=null ? user.getPassword() : "old password");
preparedStatement.setInt(4, user.getId());
preparedStatement.executeUpdate();
}
答案 0 :(得分:0)
动态构建你的sql,如下所示,并传递值dynamic index。
public void updateUser(User user){
Connection connection = dataSource.getConnection();
StringBuilder sql = new StringBuilder();
sql.append("update \"User\" set id_role = ?, fullname = ? ");
if (user.getPassword()!=null)
sql.append("password = ? ");
sql.append("WHERE id = ?"");
PreparedStatement preparedStatement = connection.prepareStatement("update \"User\" set id_role = ?, fullname = ?, password = ? WHERE id = ?");
// declare index variable to get the dynamic index
int index=1;
preparedStatement.setInt(index++, user.getIdRole());
preparedStatement.setString(index++, user.getFullName());
if (user.getPassword()!=null)
preparedStatement.setString(index++, user.getPassword());
preparedStatement.setInt(index++, user.getId());
preparedStatement.executeUpdate();
}
在上面的代码中,我们将在用户更改密码值时更新密码,否则密码值不会更新。
试一试:)
答案 1 :(得分:0)
您可以通过动态查询构建
进行以下操作# Active rewrite engine
RewriteEngine On
# Force www.
RewriteCond %{HTTP_HOST} !^www.example.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]
# If it's the homepage
RewriteCond %{REQUEST_URI} ^/?$
# Skip the next 4 rules (self-inclusion)
RewriteRule .* - [S=4]
# If url is not "index.php"
RewriteCond %{REQUEST_URI} !^/index.php [OR]
# Or does not contain "page="
RewriteCond %{QUERY_STRING} !(^|&)page=.+(&|$)
# Redirect to homepage
RewriteRule . /? [L,R=301]
和preparedStatment相同
答案 2 :(得分:0)
是的,正如Jens爵士在Servlet中所说,检查密码是否为空,并基于updateUserWithPass(用户用户)或updateUserWithoutPass(用户用户)。
部分代码
if(request.getParameter("password")!=null){
//Code for updateUserWithPass(User user);
}else{
//Code for updateUserWithoutPass(User user);
}