This question already has an answer here:
- How do I compare strings in Java? 23 answers
i'm new in AJAX and i'm trying to create a login form for my web app course using java. I'm using ajax to communicate with the servlet, and hardcode the user and password validation in the servlet just for a test. The thing is, i never get a success result and redirected to my webb apps home page even though i input the right username and password. Maybe i did something wrong in my code? Here's my HTML, Javascript, and servlet code :
HTML
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="CSS/style.css" rel="stylesheet" type="text/css"/>
<script src="script/jquery-3.1.1.min.js" type="text/javascript"></script>
<script src="script/login.js" type="text/javascript"></script>
</head>
<body>
<div id="wrapper">
<main id="loginmain">
<form name="login" id="loginform">
<div id="logo">
<img id="logoicon" src="images/Logo 1.png" alt=""/>
</div>
<p id="error">Username or Password is incorrect</p>
<input type="text" name="uname" id="uname" style="text-align: center;" value="Username" onclick="this.value='';"/>
<input type="text" name="pass" id="pass" style="text-align: center;" value="Password" onfocus="this.value='';$(this).attr('type', 'password');"/>
<input type="button" id="btnLogin" value="Login"/>
</form>
</main>
<footer><p>©Copyright 2016 Muhammad Reza Krisna 1611510171</p></footer>
</div>
</body>
Javascript
$(document).ready(function(){
$('#btnLogin').click(function(){
var user = $('#uname').val();
var pass = $('#pass').val();
$.ajax({
type: "POST",
url: "LoginServlet",
data: ({"user":user,"pass":pass}),
success: function(data) {
if(data=="true"){
$(location).attr("href","home.jsp");
}else {
$("#error").show();
}
}
});
});
});
Servlet
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//processRequest(request, response);
try{
String user = request.getParameter("user");
String pass = request.getParameter("pass");
if(user=="admin" && pass=="admin"){
HttpSession session = request.getSession();
session.setAttribute("user",user);
response.setContentType("text/plain;charset=UTF-8");
PrintWriter out = response.getWriter();
out.write("true");
}
} catch(Exception e) {
e.printStackTrace();
}
}
Aucun commentaire:
Enregistrer un commentaire