Servlet不转发到另一个JSP

时间:2011-05-30 13:46:22

标签: jsp servlets jdbc

我有一个JSP文件Signup.jsp,它提交到UserDetails servlet,它将用户详细信息插入数据库“tblusers”,并在成功插入数据后转发到ElecBill.jsp。而不是转发到ElecBill.jsp,而是转发到Signup.jsp。换句话说,插入数据失败了。

这是servlet代码:

package com.elecbill;

import java.io.*;
import java.sql.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;


public class UserDetails extends HttpServlet
{
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws javax.servlet.ServletException, IOException
{

String userid=request.getParameter("uid");
String firstname=request.getParameter("fname");
String lastname=request.getParameter("lname");
String phonenum=request.getParameter("phone");
String mobilenum=request.getParameter("mobile");
String email=request.getParameter("email");
String login=request.getParameter("loginid");
String pass=request.getParameter("pass");
String pass1=request.getParameter("pass1");
try
{

Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/elecbill","root","root");    
String query="insert into tblusers('"+userid+"','"+firstname+"','"+lastname+"','"+phonenum+"','"+mobilenum+"','"+email+"','"+login+"','"+pass+"','"+pass1+"')";

Statement s=conn.createStatement();
ResultSet rs=s.executeQuery("select * from tblusers");
boolean str=false;
while(rs.next())
{
    if((rs.getString(6).equals(login)))
    {
        str=true;
    }
}
   if(!str)
{
    s.executeUpdate(query);
    HttpSession ses=request.getSession(true);
    ses.setAttribute("login",login);
    RequestDispatcher rq=request.getRequestDispatcher("ElecBill.jsp");
    request.setAttribute("msg","Registered Successfully");
    rq.forward(request,response);
    System.out.println("Successfully");

}
  else
{
 RequestDispatcher rq=request.getRequestDispatcher("signup.jsp");
 request.setAttribute("msg","Im Already in use. Choose another Id");
 rq.forward(request,response);


}

  }
  catch (Exception e)
  {
e.printStackTrace();
  }

 }

}

这个问题是如何引起的?如何解决?

1 个答案:

答案 0 :(得分:2)

数据的插入没有失败。更重要的是,根据代码流程,它根本没有被执行。根据您的代码流,它只是意味着用户提供的loginid参数与其中一个表行的第6列的值匹配。

尝试提供不同的loginid值。


对具体问题

无关,这段代码对SQL injection attacks很敏感。使用PreparedStatement。此外,在这段代码中查找现有的登录ID非常低效,因为您将整个数据库表复制到Java的内存中并使用Java而不是SQL进行比较。了解如何使用WHERE clause并使用boolean exist = resultSet.next()