Tuesday 12 August 2014

AJAX Example With Java

Create a Servlet Class as shown below:


Note:- Before we get started with AJAX Example Let me distribute it in separate units
=> URL is important it defines where from we need to fetch the data (In our case we have servlet to be called DisplayUser).
=> What you want from Servlet based on that you can decide what parameters you need to send from your page
=> what is the format of response you need that gets defined from How will data be used internally after getting it processed from servlet


====================================================================
package com.test;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class DisplayUser
 */
@WebServlet("/DisplayUser")
public class DisplayUser extends HttpServlet {
private static final long serialVersionUID = 1L;
     
private java.sql.PreparedStatement preparedStatement = null;
private java.sql.Connection connection = null;
private ResultSet resultSet = null;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DisplayUser() {
        super();
        // TODO Auto-generated constructor stub
    }

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter(); //
try
{
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/student_library","root", "password");
String searchQuery = "SELECT * FROM USER WHERE name=?";
preparedStatement = connection.prepareStatement(searchQuery);
String name = request.getParameter("name");
preparedStatement.setString(1,name);
resultSet = preparedStatement.executeQuery();
out.println("<table width='100%' border='1' cellpadding='0' cellspacing='0'>");
out.println("<tr><th>ID</th><th>NAME</th><th>DEPARTMENT</th><th>EMAIL</th><th>PASSWORD</th></tr>");
while(resultSet.next()) {
out.print("<tr>");
out.print("<td>"+String.valueOf(resultSet.getInt("user_id"))+"</td>");
out.print("<td>"+resultSet.getString("name")+"</td>");
out.print("<td>"+resultSet.getString("department")+"</td>");
out.print("<td>"+resultSet.getString("email")+"</td>");
out.print("<td>"+resultSet.getString("password")+"</td>");
out.println("</tr>");
           }
out.println("</table>");

}
catch(SQLException e)
{
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}

}

==================================================================

JSP


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>

 <script src="http://code.jquery.com/jquery-latest.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#txtName').keyup(function(){
var nameVal = $('#txtName').val();
$.ajax({
type:"GET",
url:"http://localhost:9999/AddWebProject/DisplayUser",
data:"name="+nameVal,
async:false,
success: function(userObj){
document.getElementById("divTable").innerHTML = userObj;
},
failure:function(){
alert("No Record Found");
}
});
});
});
</script>

<body>

<%
String name="";
String dept = "";
String email = "";
String password ="";
if(request.getAttribute("duplicateUser")!=null && request.getAttribute("duplicateUser").equals("true"))
{
%>
<p style={color:red} >
Email Id Already Exists
</p>
<%
name = (String)request.getAttribute("txtName");
dept = (String)request.getAttribute("txtDepartment");
email = (String)request.getAttribute("txtEmail");
password=(String)request.getAttribute("txtPassword");
}
%>

<form action="/AddWebProject/CreateUser/" name="frmNewUser" method="post">
<label>Name:</label>
<input type="text" name="txtName" id="txtName" value='<%=name %>' /> <br/>
<label>Department</label>
<input type="text" name="txtDepartment" id="txtDepartment" value='<%=dept %>' /> <br/>
<label>Email</label>
<input type="text" name="txtEmail" id="txtEmail" value='<%=email %>'/><label id="lblErrMail" style='display:none'>Email Already Exists</label>
<br/>
<label>Password</label>
<input type="password" name="txtPassword" id="txtPassword" value='<%=password %>' /><br/>
<label>Re-Type Password</label>
<input type="password" name="txtRePassword" id="txtRePassword" value='<%=password%>' /><br/>
<input type="submit" value="Create">
<input type="reset" value="cancel"/>
</form>
<div id="divTable">

</div>
</body>
</html>

=> This is an working example that displays all the available users with the username entered in text-box.


No comments:

Post a Comment