【发布时间】:2014-02-11 17:12:02
【问题描述】:
我正在尝试通过设置属性从 Servlet 转发到 JSP,但出现以下异常:
java.lang.IllegalStateException:响应后无法转发 已承诺
请帮忙。
我的代码:
public class setPassword extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ClassNotFoundException, SQLException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Connection co;
try {
Class.forName("com.mysql.jdbc.Driver");
co = DriverManager.getConnection("jdbc:mysql://localhost:3306/gift", "root", "");
Statement st = co.createStatement();
System.out.println("setpassword...........");
ResultSet rs = st.executeQuery("select * from generaldata");
System.out.println("setpassword...........111");
String userid = request.getParameter("username");
while (rs.next()) {
String us = rs.getString(2);
String ps = rs.getString(3);
System.out.println("setpassword...........222");
System.out.println(us);
System.out.println(userid);
if (userid.equals(us)) {
System.out.println(ps);
System.out.println("setpassword...........333");
if (ps.equals("")) {
String pass = request.getParameter("password");
String pass1 = request.getParameter("password1");
System.out.println("setpassword...........444");
if (pass.equals(pass1)) {
rs.updateNString(3, pass);
RequestDispatcher rdpassword = request.getRequestDispatcher("home.jsp");
rdpassword.forward(request, response);
System.out.println("setpassword...........555");
} else {
request.setAttribute("errorPassword", "Your Password does not match...!!!");
RequestDispatcher rdlogin = request.getRequestDispatcher("newuser.jsp");
rdlogin.forward(request, response);
System.out.println("setpassword...........666");
}
} else {
request.setAttribute("err", "Please note you are not a New User...!!!");
System.out.println("setpassword.................777");
RequestDispatcher rdNotNew = request.getRequestDispatcher("login.jsp");
rdNotNew.forward(request, response);
}
} else {
request.setAttribute("err", "Not a valid User...!!!");
System.out.println("setpassword.................788");
RequestDispatcher rdNotValid = request.getRequestDispatcher("login.jsp");
rdNotValid.forward(request, response);
}
System.out.println("setpassword.................888");
}
System.out.println("setpassword.................999");
rs.close();
st.close();
co.close();
} catch (Exception e) {
System.out.println(e);
} finally {
out.close();
}
}
【问题讨论】:
-
请粘贴您的输出
-
如果请求被转发一次之前循环终止然后,即使在请求被转发之后循环仍将继续,它将尝试再次从另一个转发请求(或可能相同,具体取决于对其中一个条件的评估)
if-else的块导致笨拙的java.lang.IllegalStateException被抛出(这可能看起来不寻常)。您可能希望适当地使用break语句或if-else-if阶梯中的标志变量来指示身份验证状态并使用该变量在循环外转发请求。 -
如果您正在检查用户身份验证,您可以只使用带有准备语句的单个查询,例如
select * from user_table where user_email=? and user_password=?,然后是if(rs.next()){//User credentials are correct. So redirect to the home page}else{//Show a message indicating bad credentials}。没有必要循环跳舞:) -
感谢您提供“准备声明”的想法............