Sunday, 25 August 2013

JSON, AJAX and MVC

JSON, AJAX and MVC

I'm trying to implement JSON and AJAX to MVC design pattern through simple
login page, but i'm having an error

Here's my view:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Test Page</title>
<script src="../js/jquery-1.10.1.min.js" ></script>
<script src="../js/data_handler.js" ></script>
</head>
<body>
<form action="LoginController" method="post" id="loginForm">
<!-- Login body -->
<table>
<tr>
<td><label for="userName">Username:</label></td>
<td><input type="text" name="userName" id="userName" /></td>
</tr>
<tr>
<td><label for="password">Password:</label></td>
<td><input type="password" name="password" id="password"
/></td>
</tr>
<tr>
<td><input type="submit" /></td>
</tr>
</table>
<hr />
<p id="displayName" />
</form>
</body>
</html>
Here's my controller:
protected void doPost( HttpServletRequest request, HttpServletResponse
response ) throws ServletException,
IOException
{
Map<String, Object> map = new HashMap<String, Object>(); //
variable that will hold data to be parsed to JSON
UserDAO userDAO = new UserDAO(); // instantiate database
String userName = request.getParameter( "userName" ); // get
userName String from the Login.jsp
String password = request.getParameter( "password" ); // get
password String from the Login.jsp
boolean isValid = userDAO.authenticate( userName, password );
map.put( "isValid", isValid );
if( isValid ) // validate userName and password
{
UserModel userModel = userDAO.getUserDetails( userName ); //
get userModel that correspond to userName parameter
request.getSession().setAttribute( "userName", userName ); //
set SESSION REQUEST to be forward to MainPage.jsp
request.setAttribute( "userDetails", userModel ); // set
REQUEST to be forward to MainPage.jsp
RequestDispatcher rd = request.getRequestDispatcher(
"MainPage.jsp" );
rd.forward( request, response ); // forward request to
MainPage.jsp
return;
}
else
{
map.put( "userName", userName );
write( response, map );
}
}
/**
* @param response
* @param map contains data to parse to JSON
* @throws IOException
*/
private void write( HttpServletResponse response, Map<String, Object>
map ) throws IOException
{
response.setContentType( "application/json" );
response.setCharacterEncoding( "UTF-8" );
response.getWriter().write( new Gson().toJson( map ) );
}
Here's the AJAX:
$(document).ready(function(){
$('#loginForm').submit(function(){
$.ajax({
url: 'LoginController',
type: 'POST',
dataType: 'json',
data: $('loginForm').serialize(),
success: function(data){
alert("hello");
}
});
return false;
});
});
What i'm trying to do is a login page that if the user didn't enter a
proper USERNAME and PASSWORD an alert will appear. What am i doing wrong?
I'm just new to AJAX and JSON. For JSON i'm usingGSON`

No comments:

Post a Comment