Issue
I have been trying to develop a login page using ajax and servlet. But I haven't successfully created one. The results are always different from what I expected. I even tried referring to a previously successful file but I still failed.
These are my codes:
- index.html
<form id="loginFrm">
<div class="imgcontainer">
<img src="img_avatar2.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<input type="radio" value="Urusetia" name="loginRole">Urusetia<br>
<input type="radio" value="Penyelaras PITA" name="loginRole">Penyelaras PITA<br>
<input type="radio" value="Penyelia" name="loginRole">Penyelia<br>
<input type="radio" value="Penilai" name="loginRole">Penilai<br>
<input type="radio" value="Pelajar" name="loginRole">Pelajar<br>
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" id="username" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" id="password" required>
<button type="submit">Login</button>
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" class="cancelbtn">Cancel</button>
<span class="psw">Forgot <a href="#">password?</a></span>
</div>
</form>
- index.js
$(function(){
$("#loginFrm").submit(function(e){
e.preventDefault();
e.stopPropagation();
var username = $("#username").val();
var password = $("#password").val();
var datalist = "username="+username+"&password="+password;
$.ajax({
type:"post",
url:"LogMasuk",
data:datalist,
cache: false,
success: function(mydata){
var myData = JSON.parse(mydata);
if(myData.status === 1){
alert("Success");
sessionStorage.token = username;
location.href = "dashboard.html";
}else if(myData.status === 0){
alert("User not found.");
}
},
error: function(){
console.log("AJAX error.");
}
});
});
});
- LogMasuk.java
public class LogMasuk extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
JSONObject jo = new JSONObject();
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here. You may use following sample code. */
String username = request.getParameter("username");
String password = request.getParameter("password");
jo = dbAPI.LogMasuk(username, password);
} finally {
out.print(jo);
out.close();
}
}
and the file to refer to database
public static JSONObject LogMasuk(String username, String password){
JSONObject jo = new JSONObject();
boolean exist = false;
try{
con = conMan.getConnection();
String sql = "SELECT * FROM pelajar WHERE username=? AND password=?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
rs = ps.executeQuery();
while(rs.next()){
exist = true;
}
if(exist){
jo.put("status", 1);
}
else
jo.put("status", 0);
}
catch(SQLException e){
jo.put("status", -1);
}
return jo;
Every time I always hit {} response in the browser's console under the network tab even the status code is ok.
Thanks in advance.
Solution
Your problem is caused by bad exception handling.
Your code threw an exception, most likely a ClassNotFoundException
on the JDBC driver, but you're basically completely suppressing it by forcing the close of the response body in the finally
block.
try {
// ...
} finally {
out.print(jo);
out.close(); // BAD! Remove this line!
}
This way you're basically preventing the server from showing its default error response which usually contains a stack trace and thus effectively the answer to your real problem.
Better yet, do not handle exceptions like that in a servlet. Remove the try-finally
block altogether.
// ...
out.print(jo);
If any, you should be rethrowing any checked exception as a ServletException
in a catch
block.
try {
// ...
out.print(jo);
} catch (SomeCheckedException e) {
throw new ServletException(e);
}
This way the server will be able to properly deal with it and you can configure the error response body in web.xml
.
See also:
- Submitting form to Servlet which interacts with database results in blank page
- How should I connect to JDBC database / datasource in a servlet based application?
- How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception
Answered By - BalusC