jsp Cannot forward after response has been committed问题,
String username = request.getParameter("username");
String password = request.getParameter("password");
String confirmPassword = request.getParameter("confirmPassword");
String sql = "select username,password from users ";
QueryRunner qr = DbHelper.getQueryRunner();//工具类,数据库肯定没问题
List list = null;
User user = null;//bean类
try {
list = (List) qr.query(sql,new BeanListHandler(User.class));
} catch (Exception e) {
e.printStackTrace();
}
if (password.equals(confirmPassword)) {
for (int i = 0; i < list.size(); i++) {
user = (User) list.get(i);
if (user.getUsername().equals(username)) {
request.setAttribute("message","用户名已经被注册!");
request.getRequestDispatcher("/admin/login.jsp").forward(
request,response);
}else {
sql = "insert into users(username,password) values(?,)";
String params[] = { username,password };
qr = DbHelper.getQueryRunner();
try {
qr.update(sql,params);
} catch (SQLException e) {
e.printStackTrace();
}
request.setAttribute("message","注册成功!");
request.getRequestDispatcher("/admin/login.jsp").forward(request,
response);
}
}
}
else {
request.setAttribute("message","两次密码不一样,请重新输入");
request.getRequestDispatcher("/admin/reg.jsp").forward(request,
response);
}
人气:266 ℃ 时间:2019-12-29 15:15:30
解答
/**
1.对于转发,只能转发一次,否则抛出异常.
2.你的判断重名的逻辑有问题,你的逻辑是与list里面所有名字比较,只要不相同就入库并转发.
这将导致入库很多次,转发了很多次.而转发多次将抛出异常
正确的逻辑是应该先遍历完list,才能确定是否用户重名,最后转发一次.
3.判断逻辑有问题,应该先遍历完list,才能确定是否用户重名,一旦重名转发,并return结束
**/
//下面的代码是我修改的部分.
if (password.equals(confirmPassword)) {
for (int i = 0; i < list.size(); i++) {
user = (User) list.get(i);
if (user.getUsername().equals(username)) {
request.setAttribute("message","用户名已经被注册!");
request.getRequestDispatcher("/admin/login.jsp").forward(
request,response);
return;//必须判断完整个list列表才能确定是否重名.
}
}
sql = "insert into users(username,password) values(?,)";
String params[] = { username,password };
qr = DbHelper.getQueryRunner();
try {
qr.update(sql,params);
} catch (SQLException e) {
e.printStackTrace();
}
request.setAttribute("message","注册成功!");
request.getRequestDispatcher("/admin/login.jsp").forward(request,
response);
}
else {
request.setAttribute("message","两次密码不一样,请重新输入");
request.getRequestDispatcher("/admin/reg.jsp").forward(request,
response);
}
}
推荐
猜你喜欢