I have tried to insert the data that user inputted by using the servlet. I am following a video, but I have an error in my code.
In the video, when the user has input the data, it will display a succuss messange, but my code will display the error message (in the catch statement) after input.
I don't know why it is. Do I fail to connect to the database? If no, then what is the issue? If yes, how to solve it?
Here is my code:
index.html
:
<!DOCTYPE html><!--Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this licenseClick nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Html.html to edit this template--><html><head><title>TODO supply a title</title><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body><h1>Sign Up Form</h1><form method="get" action ="dataServ"> Enter Username:<input type="text" name="txtuname"/><br> Enter Password:<input type="password" name="txtupass"/><br/><input type="submit" value="Sign Up"/><input type="reset" value="Reset"/></form></body></html>
dataServ.java
:
import java.io.IOException;import java.io.PrintWriter;import jakarta.servlet.ServletException;import jakarta.servlet.http.HttpServlet;import jakarta.servlet.http.HttpServletRequest;import jakarta.servlet.http.HttpServletResponse;import java.sql.*;/** * * @author User */public class dataServ extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet dataServ</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet dataServ at " + request.getContextPath() +"</h1>"); out.println("</body>"); out.println("</html>"); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); java.sql.Connection con = null; java.sql.Statement stmt = null; String n = "", p = ""; n = request.getParameter("txtuname"); p = request.getParameter("txtupass"); try { Class.forName("org.apache.derby,jdbc.ClientDriver"); con = DriverManager.getConnection("jdbc:derby://localhost:1527/Accla", "ubuser", "ubuser"); stmt = con.createStatement(); stmt.executeUpdate("insert into acc values ('" + n +"','" + p +"')"); out.print("<h1>Your Name.java</h1>"); } catch (Exception e) { out.println("sorry"); } }}
Database: