java4all@1986 java. Powered by Blogger.

How to retrieve the data from table using PrepareStatement?

>> Tuesday, June 7, 2011

In this tutorial we are going to fetch the data from the database in the table from our java program using PreparedStatement.
To accomplish our goal we first have to make a class named as ServletFetchingDataFromDatabase which must extends the abstract HttpServlet class, the name of the class should be such that the other person can understand what this program is going to perform.
The logic of the program will be written inside the doGet() method which takes two arguments, first is HttpServletRequest interface
and the second one is the HttpServletResponse interface and this method can throw ServletException.
Inside this method call the getWriter() method of the PrintWriter class.
We can retrieve the data from the database only and only if there is a connectivity between our database and the java program.
To establish the connection between our database and the java program we firstly need to call the method forName() which is static in nature of the class ClassLoader.
It takes one argument which tells about the database driver  we are going to use.
Now use the static method getConnection() of the DriverManager class.
This method takes three arguments and returns the Connection object.
SQL statements are executed and  results are returned within the context of a connection.
Now your connection has been established. Now use the method prepareStatement() of the Connection object which will return the PreparedStatement object,
and takes a query as its parameter. In this query we will write the task we want to perform.
The Resultset object will be retrieved by using the executeQuery() method of the PreparedStatement object.
Now the data will be retrieved by using the getString() method of the ResultSet object.

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ServletFetchingDataFromDatabase extends HttpServlet{
  public void doGet(HttpServletRequest request,
  HttpServletResponse response) throws 
  ServletException, IOException{
  response.setContentType("text/html");
  PrintWriter pw = response.getWriter();
  String connectionURL = "jdbc:mysql://localhost/zulfiqar";
  Connection connection=null;
  try{
  Class.forName("org.gjt.mm.mysql.Driver");
  connection = DriverManager.getConnection
   (connectionURL, "root", "admin");
  PreparedStatement pst = connection.prepareStatement
  ("Select * from emp_sal");
  ResultSet rs = pst.executeQuery();
  while(rs.next()){
  pw.println(rs.getString(1) +" " 
  + rs.getString(2)+"
"); } } catch (Exception e){ pw.println(e); } pw.println("hello"); } }

Read more...

How to insert data into database from html page?

In this tutorial we are going to make program in which we are going to insert the values in the database table from the html form.

To make our program working we need to make one html form in which we will have two fields, one is for the name and the other one  is for entering the password.
At last we will have the submit form, clicking on which the values will be passed to the server.
The values which we have entered in the Html form will be retrieved by the server side program which we are going to write.
To accomplish our goal we first have to make a class named as ServletInsertingDataUsingHtml which must extends the abstract HttpServlet class,
the name of the class should be such that the other person can understand what this program is going to perform. The logic of the program will be written inside the doGet() method,
which takes two arguments, first is HttpServletRequest interface and the second one is the HttpServletResponse interface and this method can throw ServletException.
Inside this method call the getWriter() method of the PrintWriter class. We can insert the data in the database only and only if there is a connectivity between our
database and the java program. To establish the connection between our database and the java program we firstly need to call the method forName() which is static in
nature of the class Class. It takes one argument which tells about the database driver  we are going to use. Now use the static method getConnection() of the DriverManager class.
This method takes three arguments and returns the Connection object. SQL statements are executed and  results are returned within the context of a connection.
Now your connection has been established. Now use the method prepareStatement() of the Connection object which will return the PreparedStatement object
and takes one a query which we want to fire as its input.
The values which we have got from the html will be set in the database by using the setString() method of the PreparedStatement object.
If the record will get inserted in the table then output will show "record has been inserted"  otherwise "sorry! Failure".

Login.html:
<em><html>
<head>
<title>New Page 1</title>
</head>
<body>
<form method="POST" action="/InDataByHtml/ServletInsertingDataUsingHtml">
<!--webbot bot="SaveResults" U-File="fpweb:///_private/form_results.txt"
S-Format="TEXT/CSV" S-Label-Fields="TRUE" -->
<p>Enter Name:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text"
name="username" size="20"></p>
<p>Enter Password: <input type="text" name="password" size="20"></p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="submit" value="Submit" name="B1"></p>
</form>

</body>

</html></em>

ServletInsertingDataHtml
<pre class='brush:java;'>
import java.io.*;
import java.lang.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ServletInsertingDataUsingHtml extends
 HttpServlet{
  public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException{
  response.setContentType("text/html");
  PrintWriter pw = response.getWriter();
  String connectionURL = "jdbc:mysql://localhost/zulfiqar";
  Connection connection;
  try{
  String username = request.getParameter("username");
  String password = request.getParameter("password");
  pw.println(username);
  pw.println(password);
  Class.forName("org.gjt.mm.mysql.Driver");
  connection = DriverManager.getConnection
  (connectionURL, "root", "admin");
  PreparedStatement pst = connection.prepareStatement
  ("insert into emp_info values(?,?)");
  pst.setString(1,username);
  pst.setString(2,password);
  int i = pst.executeUpdate();
  if(i!=0){
  pw.println("<br>Record has been inserted");
  }
  else{
  pw.println("failed to insert the data");
  }
  }
  catch (Exception e){
  pw.println(e);
  }
  }
}
</pre> 
web.XML:
<web-app>
 <servlet>
 <servlet-name>Zulfiqar</servlet-name>
 <servlet-class>ServletInsertingDataUsingHtml</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>Zulfiqar</servlet-name>
 <url-pattern>/ServletInsertingDataUsingHtml</url-pattern>
 </servlet-mapping>
</web-app>


Read more...

How to know the session last acess time?

This example illustrates to find current  access time of session  and last access time of session.
Sessions are used to maintain state and user identity across multiple page requests.
An implementation of HttpSession represents the server's view of the session.
The server considers a session to be new until it has been joined by the client.
Until the client joins the session, isNew() method returns true.

LastAcessTime Class


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
import java.util.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LastAccessTime extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String head;
Integer count = new Integer(0);
if (session.isNew()) {
head = "New Session Value ";
} else {
head = "Old Session value";
Integer oldcount =(Integer)session.getValue("count");
if (oldcount != null) {
count = new Integer(oldcount.intValue() + 1);
}
}
session.putValue("count", count);
out.println("<HTML><BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H2 ALIGN=\"CENTER\">" + head + "</H2>\n" +
"<H4 ALIGN=\"CENTER\">Session Access Time:</H4>\n" +
"<TABLE BORDER=1 ALIGN=CENTER>\n" + "<TR BGCOLOR=\"pink\">\n" +
"<TD>Session Creation Time\n" +" <TD>" +
new Date(session.getCreationTime()) + "\n" +
"<TR BGCOLOR=\"pink\">\n" +" <TD>Last Session Access Time\n" +
" <TD>" + new Date(session.getLastAccessedTime()) +
"</TABLE>\n" +"</BODY></HTML>");
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

Description of code: In  the above servlet,  isNew() method is used to find whether session is new or old.
The getCreationTime() method is used to find  the time when session was created.
The getLastAccessedTime() method is used to find when last time session was accessed by the user.

web.xml

  LastAccessTime
  LastAccessTime
 

  LastAccessTime
  /LastAccessTime

Read more...

How to identify wheathet the session is new or old?

In this program we are going to make one servlet on session in which we will check whether the session is new or old.
To make this program firstly we need to make one class named CheckingTheSession. 
Inside the doGet() method, which takes two objects one of request and second of response.
Inside this  method call the method getWriter() of the response object.
Use getSession() of the request object, which returns the HttpSession object.
Now by using the HttpSession we can find out whether the session is new or old.

CheckingTheSession class
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class CheckingTheSession extends HttpServlet{
  protected void doGet(HttpServletRequest request, HttpServletResponse 
  response)throws ServletException, IOException {
  response.setContentType("text/html");
  PrintWriter pw = response.getWriter();
  pw.println("Checking whether the session is new or old
"); HttpSession session = request.getSession(); if(session.isNew()){ pw.println("You have created a new session"); } else{ pw.println("Session already exists"); } } }
web.xml

 
  Hello
  CheckingTheSession
 
 
 Hello
 /CheckingTheSession
 

Read more...

What is ment by Session Tracking Mechanism?How many types of Session Tracking Mechanisms are there?

As we know that the Http is a stateless protocol, means that it can't persist the information.
It always treats each request as a new request. In Http client makes a connection to the server,
sends the request., gets the response, and closes the connection.
In session management client first make a request for any servlet or any page,
the container receives the request and generate a unique session ID and gives it back to the client along with the response.
This ID gets stores on the client machine. Thereafter when the client request again sends a request to the server then it also sends the session Id with the request.
There the container sees the Id and sends back the request.

Session Tracking can be done in three ways:

Hidden Form Fields: This is one of the way to support the session tracking. As we know by the name,
that in this fields are added to an HTML form which are not displayed in the client's request.
The hidden form field are sent back to the server when the form is submitted.
In hidden form fields the html entry will be like this : .
This means that when you submit the form, the specified name and value will be get included in get or post method.
In this session ID information would be embedded within the form as a hidden field and submitted with the Http POST command.

URL Rewriting: This is another way to support the session tracking. URLRewriting can be used in place where we don't want to use cookies.
It is used to maintain the session. Whenever the browser sends a request then it is always interpreted as a new request because http protocol is a stateless protocol as it is not persistent.
Whenever we want that out request object to stay alive till we decide to end the request object then, there we use the concept of session tracking.
In session tracking firstly a session object is created when the first request goes to the server.
Then server creates a token which will be used to maintain the session. The token is transmitted to the client by the response object and gets stored on the client machine.
By default the server creates a cookie and the cookie get stored on the client machine.

Cookies: When cookie based session management is used, a token is generated which contains user's information,
is sent to the browser by the server. The cookie is sent back to the server when the user sends a new request.
By this cookie, the server is able to identify the user. In this way the session is maintained.
Cookie is nothing but a name- value pair, which is stored on the client machine.
By default the cookie is implemented in most of the browsers. If we want then we can also disable the cookie.
For security reasons, cookie based session management uses two types of cookies.

Read more...

Example on sendRedirect Mechanism?

When we want that someone else should handle the response of our servlet, then there we should use send Redirect() method.
In send Redirect whenever the client makes any request it goes to the container, there the container decides whether the concerned servlet can handle the request or not.
If not then the servlet decides that the request can be handle by other servlet or jsp.
Then the servlet calls the send Redirect() method of the response object and sends back the response to the browser along with the status code.
Then the browser sees the status code and look for that servlet which can now handle the request.
Again the browser makes a new request, but with the name of that servlet which can now handle the request and the result will be displayed to you by the browser.
In all this process the client is unaware of the processing.
In this example we are going to make one html in which we will submit the user name and his password.
The controller will check if the password entered by the user is correct or not.
If the password entered by the user is correct then the servlet will redirect the request to the other servlet which will handle the request.
If the password entered by the user is wrong then the request will be forwarded to the html form.

HTML file:
<em><html>

<head>
<title>New Page 1</title>
</head>

<body>

<form method="POST" action="/SendRedirect/SendRedirectServlet">
<p>Enter your name��������
<input type="text" name="username" size="20"></p>
<p>Enter your password� <input type="text" name="password"
size="20"></p>
<p>����������
�� ���������
����������
��
<input type="submit" value="Submit" name="B1"></p>
</form>

</body>

</html>.</em>
SendRediectservlet Class
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SendRedirectServlet extends HttpServlet{
  protected void doPost(HttpServletRequest request, HttpServletResponse
    response)throws ServletException, IOException {
  response.setContentType("text/html");
  PrintWriter pw = response.getWriter();
  String name = request.getParameter("username");
  String password = request.getParameter("password");
  if(name.equals("James")&& password.equals("abc")){
  response.sendRedirect("/SendRedirect/ValidUserServlet");
  }
  else{
  pw.println("u r not a valid user");
  }
  }
} 
ValidUserServlet class 
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ValidUserServlet extends HttpServlet{
protected void doGet(HttpServletRequest request, HttpServletResponse
  response)throws ServletException, IOException {
  PrintWriter pw = response.getWriter();
  pw.println("Welcome to roseindia.net " + " ");
  pw.println("how are you");
}
}
WEB.XML FILE:

 
 Zulfiqar
 SendRedirectServlet
 
 
 Zulfiqar
 /SendRedirectServlet
 
 
 Hello
 ValidUserServlet
 
 
 Hello
 /ValidUserServlet
 

Read more...

How to run a servlet?

To run a servlet one should follow the steps illustrated below:

   1.) Download and Install the tomcat server: Install the tomcat server in a directory in which you want to install and set the classpath.for the variable JAVA_HOME in the environment variable. To get details about the installation process and setting the classpath click the link Tomcat installation.

   2.) Set the class for the jar file: Set the classpath of the servlet-api.jar file in the variable CLASSPATH inside the environment variable by using the following steps.

    For Windows XP,

   3.) Go to Start->Control Panel->System->Advanced->Environment Variables->New button and Set the values as
    Variable Name:  CLASSPATH
    Variable Value:  C:\Program Files\Java\Tomcat 6.0\lib\servlet-api.jar

    For Windows 2000 and NT

   4.) Go to Start->Settings->Control Panel->System->Environment Variables->New button and Set the values as
    Variable Name:  CLASSPATH
    Variable Value:  C:\Program Files\Java\Tomcat 6.0\lib\servlet-api.jar

    Create a java source file and a web.xml file in a directory structure.

    Compile the java source file, put the compiled file (.class file) in the classes folder of your application and deploy the directory of your application in the webapps folder inside the tomcat directory.

    Start the tomcat server, open a browser window and type the URL http://localhost:8080/directory (folder name of your application) name/servler name and press enter.

    If everything is correct your servlet will run.

Read more...

FaceBook Login

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

Total Pageviews

STATCOUNTER

  © Blogger template Simple n' Sweet by Ourblogtemplates.com 2009

Back to TOP