Issue
I am trying to get the servlet program to connect with the database and perform actions. In eclipse, when I put the connection and queries in the main() method and choose "Run as java application" it is working and the database is being updated, however, when I launch the html using "Run on server" and put the queries in the doGet() method, the servlet is running and html is being updated in the browser, but, no update is being done in the database. I also tried putting the code in the main method and calling main() through doGet() with no success.
html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Register</title>
</head>
<body>
<form action="register" method="get">
<label for="uname">Username:</label>
<input type="text" name="uname">
<label for="pwd">Password:</label>
<input type="text" name="pwd">
<button type="submit">Register</button>
</form>
</body>
</html>
doGet() method:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// response.getWriter().append("Served at: ").append(request.getContextPath());
PrintWriter pw = response.getWriter();
String uname = request.getParameter("uname");
String pwd = request.getParameter("pwd");
Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/advjavada", "root", "");
if(!con.isClosed()) {
System.out.println("Connection SUCCESSFUL!");
PreparedStatement ps = con.prepareStatement("insert into userdata(uname, pwd) value('sample2', 'sampass2');");
//ResultSet rs = ps.executeQuery();
ps.executeQuery();
}
else {
System.out.println("Connection FAILED!");
}
}
catch (Exception e) {
System.err.print(e.getMessage());
}
pw.println("<h1>Hello, " + uname + "!</h1><p>Registration Successful</p>");
pw.close();
}
Solution
Tahir Hussain Mir's answer on this question has resolved the issue.
As it turns out, it's a problem during deployment in which the external jar file for SQL is used for compilation but is not included during runtime.
To solve this:
Add the .jar
file to the Deployment Assembly
under Project > Properties
.
Answered By - sighclone
Answer Checked By - Timothy Miller (JavaFixing Admin)