当前位置: > jsp Cannot forward after response has been committed问题,...
题目
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();

提问时间:2020-09-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);
}
}
举一反三
已知函数f(x)=x,g(x)=alnx,a∈R.若曲线y=f(x)与曲线y=g(x)相交,且在交点处有相同的切线,求a的值和该切线方程.
我想写一篇关于奥巴马的演讲的文章,写哪一篇好呢?为什么好
奥巴马演讲不用看稿子.为什么中国领导演讲要看?
想找英语初三上学期的首字母填空练习……
英语翻译
版权所有 CopyRight © 2012-2019 超级试练试题库 All Rights Reserved.