Reputation: 67
"Here is code after inserting data its cannot forwarding the index page please help me..... and after that i am not able to fetch data also... " '
public class insertData extends HttpServlet {
String query;
static Connection conn;
//Statement st;
PreparedStatement pst;
ResultSet res;
ConnectionManager dbconn;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
dbconn= new ConnectionManager();
String id=request.getParameter("id");
String fname=request.getParameter("fname");
String lname=request.getParameter("lname");
String pass=request.getParameter("pass");
String mobile=request.getParameter("mbl");
String email=request.getParameter("email");
conn=dbconn.getConnection();
//pst=conn.createStatement();
pst=conn.prepareStatement ("INSERT INTO reg(`id`, `fname`, `lname`, `pass`, `mbl`, `email`) VALUES (?,?,?,?,?,?)");
// query="insert into reg(id('"+id+"','"+fname+"','"+lname+"','"+pass+"','"+mobile+"','"+email+"')";
pst.setString(1, id);
pst.setString(2, fname);
pst.setString(3, lname);
pst.setString(4, pass);
pst.setString(5, mobile);
pst.setString(6,email);
int i=pst.executeUpdate();
}
catch(Exception e)
{
//System.out.println("Exception"+e.getMessage());
request.setAttribute("Error",e);
RequestDispatcher rd=request.getRequestDispatcher("/error.jsp");
rd.forward(request, response);
}
finally
{
RequestDispatcher rd=request.getRequestDispatcher("/index.jsp");
rd.forward(request, response);
}
}
'
so......how can i fix this please help me...thanks in advance for help
Upvotes: 1
Views: 1621
Reputation: 1575
When an exception occur as per above code it will forward the request using RequestDispatcher
to error.jsp. Once this happen your Request is committed and now you cant do anything more with it.
But you have a finally
block - which will get executed irrespective of the fact try block being successful or throwing an exception. You are again trying to get an RequestDispatcher
there and forward to index.jsp and hence getting the above error.
Not sure of your exact use case but feel you can redirect to your index.jsp
as last step of Try
block itself.And remove the finally block altogether.
One more thing to note is its not advised to write your JDBC/DB related code in Servlet
itself you can create a separate DAO
class for that and it will lead to better abstraction and modularity.
Upvotes: 1