I have a JSP file Signup.jsp
which submits to UserDetails
servlet which inserts the user details in the database "tblusers" and forwards to ElecBill.jsp
after successful data insertion. Instead of forwards to ElecBill.jsp
it is forwarding to Signup.jsp
. In other words, insertion of data has failed.
Here is the servlet code:
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();
}
}
}
How is this problem caused and how can I solve it?
The insertion of the data hasn't failed. Even more, according to the code flow it isn't been executed at all. According to your code flow, it just means that the user-supplied loginid
parameter has a match with the value of the 6th column of one of the table rows.
Try supplying a different loginid
value.
Unrelated to the concrete problem, this piece of code is sensitive to SQL injection attacks. Use PreparedStatement
. Also, finding an existing login ID is in this piece of code very inefficient as you're copying the entire DB table into Java's memory and doing the comparison in Java instead of in SQL. Learn how to use the WHERE
clause and just use boolean exist = resultSet.next()
.
精彩评论