java4all@1986 java. Powered by Blogger.
Showing posts with label Servlets. Show all posts
Showing posts with label Servlets. Show all posts

How to use the context log in servlets?

>> Monday, June 13, 2011

This example illustrates about how to use of Context Log in servlet.
Context Log is used to write specified message to server log file when servlet is called.
In the following JSP page (message.jsp) we have simply taken a text area where user give,
his/her message and post the form. After posting the form, the servlet ContextLogExample is called.
Source code of the message.jsp is given below:

message.jsp
<%@page language="java" session="true" contentType="text/html;charset=ISO-8859-1"%>
<br>
<form name="frm" method="post" action=../ContextLogExample>
<table border = "0">
<tr align="left" valign="top">
<td>Give your Message:</td>
</tr>
<tr>
<td><TEXTAREA NAME="message" COLS=30 ROWS=6></TEXTAREA></td>
</tr>
<tr align="left" valign="top">
<td><input type="submit" name="submit" value="submit"/></td>
</tr>
</table>
</form>

when we run the program we will get output as below
In the following servlet  (ContextLogExample) we get parameter of jsp page in "message"
variable and set this message to the log file by log() method of ServletContext interface
ContextLogExample.java:

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

public class ContextLogExample extends HttpServlet {
  public void doPost(HttpServletRequest request, 
HttpServletResponse response)
  throws ServletException, IOException{
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  
  String message = request.getParameter("message");
  ServletContext context = getServletContext();
  if(message == null || message.equals("")){
  context.log("No message received:", 
new IllegalStateException("Parameter not Found"));
  }else{
  context.log("Parameter Found: Successfully 
received your message: " + message);
  }
  out.println("<html><head><title>Context Log 
Example</title></head><body>");
  out.println("<h2><font color='green'>Successfully 
send your Message</font></h2>");
  out.println("</body></html>");
  } 
}
 
web.xml
<servlet>

        <servlet-name>ContextLogExample</servlet-name>

        <servlet-class>ContextLogExample</servlet-class>

      </servlet> 

      <servlet-mapping>

        <servlet-name>ContextLogExample</servlet-name>

        <url-pattern>/ContextLogExample</url-pattern>

      </servlet-mapping>
User enter the message as below
 Servlet sets the message in the log file which is shown like below:
 
  
 

Read more...

How can we will provide control over log files in server using Filters in servlets?

This example illustrates how one can write Logging Filter servlet to provide control over log file.
You can have additional controls over these log files and these all are available to use by implementing "Filter" class.
Filters are very important in servlet access and handling due to number of reasons, for example,
it encapsulates recurring tasks in a reusable unit, modularizing codes so that they become easy to manage,
transforming request from a servlet to JSP page. Most common task for a web application is to format data sent back to client,
since most clients require different format (e.g in WML,XML etc.) rather than only HTML so to accomplish these tasks of clients,
Filtering is important to develop a fully featured Web Application. Filters can perform many different tasks,
in which logging is one of the most important task. You can create filter class by implementing javax.servlet.Filter, which has three methods as follows:

 1.void init(FilterConfig filterConfigObject) throws ServletException
 2.void destroy()
 3.void doFilter(ServletRequest request, ServletResponse response, FilterChain filterchainObject)
    throws IOException, ServletException

init(FilterConfig) is called once by the server to get prepared for service and then it calls doFilter() number of times for request processing.

In this example there is LoggingFilterExample servlet which is writing Remote Address, URI , Protocol of calling JSP file into log file as server calls LoggingFilterExample via logging.jsp. Source code for LoggingFilterExample.java is given as below:

LoggingFilterExample.java:
    
Logging Filter Servlet Example
Posted on: July 5, 2008 at 12:00 AM
This example illustrates how one can write Logging Filter servlet to provide control over log file.
Logging Filter Servlet Example

     

Example program to demonstrate Logging Filter

This example illustrates how one can write Logging Filter servlet to provide control over log file. You can have additional controls over these log files and these all are available to use by implementing "Filter" class. Filters are very important in servlet access and handling due to number of reasons, for example, it encapsulates recurring tasks in a reusable unit, modularizing codes so that they become easy to manage, transforming request from a servlet to JSP page. Most common task for a web application is to format data sent back to client since most clients require different format (e.g in WML,XML etc.) rather than only HTML so to accomplish these tasks of clients, Filtering is important to develop a fully featured Web Application. Filters can perform many different tasks, in which logging is one of the most important task. You can create filter class by implementing javax.servlet.Filter, which has three methods as follows:

    void init(FilterConfig filterConfigObject) throws ServletException
    void destroy()
    void doFilter(ServletRequest request, ServletResponse response, FilterChain filterchainObject) 
    throws IOException, ServletException

init(FilterConfig) is called once by the server to get prepared for service and then it calls doFilter() number of times for request processing. 

In this example there is LoggingFilterExample servlet which is writing Remote Address, URI , Protocol of calling JSP file into log file as server calls LoggingFilterExample via logging.jsp. Source code for LoggingFilterExample.java is given as below:

1. LoggingFilterExample.java
mport java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public final class LoggingFilterExample implements Filter 
{
  private FilterConfig filterConfigObj = null;

  public void init(FilterConfig filterConfigObj) {
  this.filterConfigObj = filterConfigObj;
  }

  public void doFilter(ServletRequest request, 
ServletResponse response,
  FilterChain chain)
  throws IOException, ServletException 
  {
  String remoteAddress =  request.getRemoteAddr();
  String uri = ((HttpServletRequest) request).getRequestURI();
  String protocol = request.getProtocol();

  chain.doFilter(request, response);
  filterConfigObj.getServletContext().log("Logging 
Filter Servlet called");
    filterConfigObj.getServletContext().log("*******
*******************");
  filterConfigObj.getServletContext().log("User 
Logged ! " + User IP: " + remoteAddress + 
   " Resource File: " + uri + " 
Protocol: " + protocol);
  }

  public void destroy() { }
}
logging.jsp
<%@ page language="java" %>
<html>
<head>
<title>Logging Filter Example</title>
</head>
<body>
<h1>Logging Filter</h1>
This filter writes log file of Tomcat Web Server.
<hr>
See log file of Web server.
<br>
</body>
</html>

 When this JSP file is called by the server then through the filter mapping LoggingFilterExample filter
would be called and it will write content into log file of your web server.
To do working we have to do mapping in the web.xml deployment descriptor.
<filter> and <filter-mapping> element requires <filter-name> to tell the name of filter,
to which you want to map a servlet or URL pattern. This mapping is as follows:
web.xml
<display-name>Welcome to Tomcat</display-name>
  <description>Welcome to Tomcat</description>
  <filter>
   <filter-name>LoggingFilterExample</filter-name>
  <filter-class>LoggingFilterExample</filter-class>
  </filter>
  <filter-mapping>
  <filter-name>LoggingFilterExample</filter-name>
  <url-pattern>/logging.jsp</url-pattern>
  </filter-mapping>
</web-app>

To run this example you have to follow these few steps given as below:

   1.Create and Save LoggingFilterExample.java
   2.Compile and put this LoggingFilterExample.java into classes folder
   3. Create and save logging.jsp
   4. Do the filter-mapping in web.xml
   5. Start Tomcat web server
   6. Type following URL into address bar
    http://localhost:8080/vin/logging.jsp


output will be


      and now go and see your tomcat's logs/localhost.<current date>.log file.
Last few lines in this file would be like this.

   

Read more...

Refreshing a webpage using Servlets?

In this simplified example we develop an application to Refresh a web Page using Servlet.
We create two file timer.html and timer.java. When a web page ("timer.html") run on browser,
then it will call to Servlet ("timer.java") and refresh this web page and print the current Date
and Time after 10 sec on the browser as a output.

Step 1: Create a web page(timer.html) to call a Servlets.

timer.html
<HTML>
 <HEAD>
  <TITLE>Refresh Servlet Timer</TITLE>
  <META NAME="Generator" CONTENT="EditPlus">
  <META NAME="Author" CONTENT="">
  <META NAME="Keywords" CONTENT="">
  <META NAME="Description" CONTENT="">
  <style type="text/css">
A:link {text-decoration: none;
    padding: 3px 7px;
    margin-right: 3px;
 
    border-bottom: none;
 
    color: #2d2b2b;  }
A:visited {text-decoration: underline;
    padding: 3px 7px;
    margin-right: 3px;
   
  
    color: #2d2b2b; }
A:active {text-decoration: none}
A:hover {text-decoration: none;
    padding: 3px 7px;
    margin-right: 3px;
    border: 0px;

    color: #2d2b2b; }
</style>

 
 </HEAD>

 <BODY>
 <br><br><br> <br><br><br>
 <table width="200px" height="100px" 
  align="center" bgcolor="#BBFFFF" border=0>
 <tr> 
      <td style="text-align:top;" valign="middle" 
      align="center" border=0>
   <a href="timer" ><b>Refresh Servlet Timer</b></a>
    </td>
 </tr>

 </BODY>
</HTML>quot;);
Step 2:Create a Servlet (timer.java) which refresh the page after every 10 seconds.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;


public class timer extends HttpServlet{ 
 public void doGet(HttpServletRequest request, 
  HttpServletResponse response)
  throws ServletException,IOException{
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  Date now = new Date(); // The current date/time
  out.println("<html>");
  out.println("<head><title> Time Check </title></head>");
  out.println("<body>");
  out.println
  ("<table  width='100%' align='center' valign='top'>");
  out.println("<tr>");
  out.println("<td>&nbsp;");
  out.println("</td>");
  out.println("</tr>");
  out.println("</tr>");
  out.println("<tr>");
  out.println("<td valign='top' align='center' valign='top'>");
  out.println
   ("<p style='color:#00000;font-size:20pt'>"+
  "<b>The Time is Refresh After 10 Seconds.</b></p>");
  out.println("<td>");
  out.println("</tr>");
  out.println("<tr>");
  out.println("<td>&nbsp;");
  out.println("</td>");
  out.println("</tr>");
  out.println("</tr>");
  out.println("<tr>");
  out.println("<td>&nbsp;");
  out.println("</td>");
  out.println("</tr>");
  out.println("</tr>");
  out.println("<tr>");
  out.println("<td style='background-color:#C6EFF7;color:blue;'"+
  " width='50' align='center'>");
  out.println("<b>The current time is: " + now + "</b>");
  out.println("</td>");
  out.println("</tr>");
  out.println("<table>");
  out.println("</body></html>"); 
  response.setHeader("Refresh", "10");
  
  }
}

Step 3: Mapping the servlet (timer.java) in to web.xml file:


Welcome to Tomcat

Welcome to Tomcat


timer
timer


timer
/timer



Step 4: Now compile the java code using javac command from command prompt.
Step 5: Start tomcat and type http://localhost:8080/timer/timer.html in the browser and Click on Text Link "Refresh Servlet Timer" . Your browser should display the Current Time and Refresh after 10 seconds.

Read more...

How to read a text file in Servlets?

In this example we will use the input stream to read the text from the disk file.
The InputStreamReader class is used to read the file in servlets program. You can use this,
code in your application to read some information from a file.

Create a file message.properties in the /WEB-INF/ directory.
We will read the content of this file and display in the browser.

Get the file InputStream using ServletContext.getResourceAsStream() method.
If input stream is not equal to null, create the object of InputStreamReader and pass,
it to the BufferedReader. A variable text is defined of String type. Read the file,
line by line using the while loop  ((text = reader.readLine()) != null). Then the writer.println(text),
is used to display the content of the file
Here is the file message.properties which is going to be read through a servlets.


Hello World!

Where there is a will, there is a way

ReadTextFile.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class ReadTextFile extends HttpServlet {
  protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
  
  response.setContentType("text/html");
  String filename = "/WEB-INF/message.properties";
  ServletContext context = getServletContext();
  
  InputStream inp = context.getResourceAsStream(filename);
  if (inp != null) {
  InputStreamReader isr = new InputStreamReader(inp);
  BufferedReader reader = new BufferedReader(isr);
  PrintWriter pw = response.getWriter();
  

  pw.println("<html><head><title>Read Text File</title></head>
   <body bgcolor='cyan'></body></html>");
  
  while ((text = reader.readLine()) != null) {
  pw.println("

"+text+"


"); } } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }

Read more...

Uses Of Cookie in Servlets?

This section illustrates you how cookie is used in Servlet.
The cookie class provides an easy way for servlet to read, create,
and manipulate HTTP-style cookies, which allows servlets to store small amount of data.
Cookies are small bits of textual information that a Web server sends to a browser and that
the browser returns unchanged when visiting the same Web site.
A servlet uses the getCookies() method of HTTPServletRequest to retrieve cookies as request.
The addCookie() method of HTTPServletResponse sends a new cookie to the browser.
You can set the age of cookie by setMaxAge() method.
The below code shows how to set maximum Age cookie.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class UseCookies extends HttpServlet { 
  public void doGet ( HttpServletRequest request,HttpServletResponse response )throws ServletException, IOException {
  PrintWriter out;
  response.setContentType("text/html");
  out = response.getWriter();
  Cookie cookie = new Cookie("CName","Cookie Value");
  cookie.setMaxAge(100);
  response.addCookie(cookie);
  
  out.println("<HTML><HEAD><TITLE>");
  out.println(" Use of cookie in servlet");
  out.println("</TITLE></HEAD><BODY BGCOLOR='cyan'>");
  out.println(" <b>This is a Cookie example</b>");
  out.println("</BODY></HTML>");
  out.close();

    }
}


In the above example, a servlet class UseCookies defines the cookie class.
Here  the age of cookie has been set as setMaxAge(100). If its value is set to 0,
the cookie will delete immediately. After the time provided been expired,
cookie will automatically deleted.

Read more...

How to retrieve Image from DataBase using Servlets?

In this example we will show you how to develop a Servlet that connects to the MySQL database and retrieves the image from the table.
After completing this tutorial you will be able to develop program for your java based applications that retrieves the image from
database. You can use this type of program to retrieve the employee image in HR application.
In case social networking site you can save the user's photo in database and then retrieve the photo for display.

Our Servlet connects to the MySQL database and then retrieves the saved password.
Here is the structure of MySQL table used in this program.

In this example the Image field will be blob and access by image id.
How to Compile Servlet program

1. Save your file same name as class name.

2. Map your servlet in web.xml file.

3. Open Command Prompt and give appropriate path of your class file.

4.  Compile your servlet class file by using javac file_name.java .

5. Run your program on the Browser by url-pattern which is define in web.xml file.

MySql Table Structure:
CREATE TABLE `pictures` (`id` int(11) NOT NULL auto_increment,`image` blob,PRIMARY KEY (`id`))
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DisplayImage extends  HttpServlet{

  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
  //PrintWriter pw = response.getWriter();
  String connectionURL = "jdbc:mysql://192.168.10.59:3306/example";
  java.sql.Connection con=null;
  try{  
  Class.forName("com.mysql.jdbc.Driver").newInstance();
  con=DriverManager.getConnection(connectionURL,"root","root");  
  Statement st1=con.createStatement();
  ResultSet rs1 = st1.executeQuery("select image from"+
   " pictures where id='5'");
  String imgLen="";
  if(rs1.next()){
  imgLen = rs1.getString(1);
  System.out.println(imgLen.length());
    }  
  rs1 = st1.executeQuery("select image from pictures where id='5'");
  if(rs1.next()){
  int len = imgLen.length();
  byte [] rb = new byte[len];
  InputStream readImg = rs1.getBinaryStream(1);
  int index=readImg.read(rb, 0, len);  
  System.out.println("index"+index);
  st1.close();
  response.reset();
  response.setContentType("image/jpg");
  response.getOutputStream().write(rb,0,len);
  response.getOutputStream().flush();  
     }
  }
  catch (Exception e){
  e.printStackTrace();
     }
  }
}

Read more...

How to insert image into database using servlets?

This example illustrate the process of inserting image into database table using Servlet. This type of program is useful in social networking or HR application where it is necessary to save the uploaded photograph of the user. If the image is stored in the database you can easily retrieve using JDBC program.
In the next section you will see a program to retrieve the image from database using Servlet.
After retrieving the image from database you can display it on the browser.

This type of program is really very useful, which makes your program very attractive.
How to Compile Servlet program

1. Save your file ImageInsertInTable.java .

2. Open Command Prompt and set the class path so that it includes the servlet api jar file.
The servlet api is available in servlet-api.jar file which you can take from tomcat's lib directory.

3. Map your servlet in web.xml file.

web.xml

ImageInsertInTable
ImageInsertInTable
 


ImageInsertInTable
/ImageInsertInTable


4. Compile your servlet class file by using javac .

command prompt> javac ImageInsertInTable.java

5. Move the class file into WEB-INF/classes directory.

6. Run your program on the Browser by url-pattern which define in web.xml file.

You should type http://localhost:8080/MyApplication/ImageInsertInTable in your browser to test the application.

MySql Table Structure:

Here is the table structure used to store the image into database. Please not the filed type used is blog
CREATE TABLE `pictures` (
`id` int(11) NOT NULL auto_increment,
`image` blob,
PRIMARY KEY (`id`)
)
ImageInsertInTable.java
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ImageInsertInTable extends  HttpServlet{
  public void doGet(HttpServletRequest request, 
  HttpServletResponse response) 
  throws ServletException, IOException{
  PrintWriter pw = response.getWriter();
  String connectionURL = 
  "jdbc:mysql://192.168.10.59:3306/example";
  Connection con=null;
  try{
  Class.forName("com.mysql.jdbc.Driver").newInstance();
  con = DriverManager.getConnection(connectionURL, "root", "root");
  PreparedStatement ps = con.prepareStatement("INSERT INTO pictures VALUES(?,?)");
  File file =new File("C:/apache-tomcat-6.0.16/webapps/CodingDiaryExample/images/5.jpg");
  FileInputStream fs = new FileInputStream(file);
  ps.setInt(1,8);
  ps.setBinaryStream(2,fs,fs.available());
  int i = ps.executeUpdate();
  if(i!=0){
  pw.println("image inserted successfully");
  }
  else{
  pw.println("problem in image insertion");
  }  
  }
  catch (Exception e){
  System.out.println(e);
  }
  }
}


ProgramDescription:
Program description:
The following code is actually used to save the image data into database.
  PreparedStatement ps = con.prepareStatement("INSERT INTO pictures VALUES(?,?)");
  File file = new File("C:/apache-tomcat-6.0.16/webapps/CodingDiaryExample/images/5.jpg");
  FileInputStream fs = new FileInputStream(file);
  ps.setInt(1,8);
  ps.setBinaryStream(2,fs,fs.available());
  int i = ps.executeUpdate();

Output:
When you run the application through browser it will display the following message, once image is successfully inserted into database.
Image is inserted Sucessfully:

Read more...

What is meant by ServletContext and Example?

>> Sunday, June 12, 2011

ServletContext:ServletContext is a interface which helps us to communicate with the servlet container.
 There is only one ServletContext for the entire web application and the components of the web application can share it.
 The information in the ServletContext will be common to all the components.
Remember that each servlet will have its own ServletConfig.
 The ServetContext is created by the container when the web application is deployed and after that only the context
 is available to each servlet in the web application.

Web Application Initialization:
 1.First of all the web container reads the deployment descriptor file and then creates a name/value pair for each <context-param> tag.

2.After creating the name/value pair it creates a new instance of ServletContext.
Its the responsibility of the Container to give the reference of the ServletContext to the context init parameters.

3.The servlet and jsp which are part of the same web application can have the access of the ServletContext.

4.The Context init parameters are available to the entire web application not just to the single servlet like servlet init parameters.

How can we do the mapping of the Context init parameters in web.xml

           <servlet>
  <servlet-name>Mapping</servlet-name>
  <servlet-class>ContextMapping</servlet-class>
</servlet>

<context-param>
  <param-name>Email</param-name>
  <param-value>admin@roseindia.net</param-value>
</context-param>

In the servlet code we will write this as

ServletContext context = getServletContext();
pw.println(context.getInitParameter("Email");

Read more...

What is meant by sendRedirect and example?

>> Friday, June 10, 2011

Send Redirect:   When we want that someone else should handle the response of our servlet,
then there we should use sendRedirect() 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 sendRedirect() 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.

                                  

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Redirecting the page</title>
</head>
<body>
<form action = "/ServletProject/SendRedirect" method = "post">
<tr>
<td>Enter your name :</td>
<td><input type = "text" name = "username"></td>
</tr><br>
<tr>
<td>Enter your password :</td>
<td><input type = "password" name = "password"></td>
</tr><br>
<tr>
<td><input type = "submit" name = "submit"></td>
</tr>
</form>
</body>
</html>
SendRedirct.class
import java.io.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SendRedirect extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
public SendRedirect() {
super();
} 
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws 
ServletException, IOException {
// TODO Auto-generated method stub
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("/ServletProject/ValidUser");
}
else
{
pw.println("u r not a valid user");
}
} 
}
validuser.class
import java.io.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class for Servlet: ValidUser
*
*/
public class ValidUser extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#HttpServlet()
*/
public ValidUser() {
super();
} 

/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws 
ServletException, IOException {
// TODO Auto-generated method stub

} 

/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws 
ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter pw = response.getWriter();
pw.println("Welcome to roseindia.net
"); pw.println("how are you"); } }

Read more...

How to change the column name in databae table?

>> Wednesday, June 8, 2011

We make a table for storing some type of data. Table keeps the data in the form of rows and columns.
Column indicates the field while row indicate the data of the field. Now consider a scenario where we have
a table and it consists some data and a situation arises where there is a need to change the name of the column.
As this is not the work of the programmer to change the name of the field, but as a programmer we should be aware how we can,
change the name of the column.
The name of the column of the column will be changed by using the simple query. But before going into it,
we should see what are the initial steps to get the desired results. First of all make a database connection with your program.
When the connection has been established pass a query for changing the column name in the preparedStatement().
This will return the PreparedStatement object.

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

public class ServletChangingColumnName 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;
  try{
  Class.forName("org.gjt.mm.mysql.Driver");
  connection = DriverManager.getConnection(connectionURL,
    "root","admin");
  PreparedStatement pst = connection.prepareStatement
  ("alter table emp_details change firstname Name varchar(10)");
  int i = pst.executeUpdate();
  pw.println("The name of the column has been changed");
      }
  catch(Exception e){
  pw.println("The exception is " + e);
     }
  }
}
web.xml:

<web-app>
 <servlet>
 <servlet-name>bhaskar</servlet-name>
 <servlet-class>ServletChangingColumnName</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>bhaskar</servlet-name>
 <url-pattern>/ServletChangingColumnName</url-pattern>
 </servlet-mapping>
</web-app>

Read more...

How to add a column into the table?

Consider a situation where the requirement of the client gets changed and you have asked to modify the structure of the table.
In reality it is the work of the database administrator but as a Java programmer you should know how you can modify the structure
of the table. The problem is that we have to add a new column to our database by using the java program.
There is no need to get panic. What we simply need is to use a query for adding a new column in the database table.
To get the desired result firstly we need to make a connection with our database. After connection has been established
pass the query in the prepareStatement() for adding new column in the database. This method will return the PreparedStatement object.
By the object of the PreparedStatement we will call the executeUpdate() which will tell the status of  the table.

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

public class ServletAddingNewColumn 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;
  try{
  Class.forName("org.gjt.mm.mysql.Driver");
  connection = DriverManager.getConnection(connectionURL, "root", 
  "admin");
  PreparedStatement pst = connection.prepareStatement
  ("alter table emp_details add column sal int(5)");
  int i = pst.executeUpdate();
  if (i==1){
  pw.println("Column has been added");
  }
  else{
  pw.println("No column has been added");
  }
  }
  catch(Exception e){
  pw.println("The exception is " + e);
  }
  }
}
web.xml file

<web-app>
 <servlet>
 <servlet-name>bhaskar</servlet-name>
 <servlet-class>ServletAddingNewColumn</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>bhaskar</servlet-name>
 <url-pattern>/ServletAddingNewColumn</url-pattern>
 </servlet-mapping>
</web-app>

Read more...

How to get number of rows in a table?

Consider a situation where we want to know about the number of rows in the particular database table,
without touching our database. As we are the programmers so why we should worry about the database complexities.
We want to find out the number of rows without going touching our back- end.
In this example we are going to exactly the same as we said above. To make this possible we need to make a class
named ServletGettingNoOfRows,  the name of the program should be such,  if in future there is any need to make any change in the program,
you can easily understand in which program you have to make a change.
As we know that in Servlet the main logic of the program is written inside the service method and in turn the service method calls the doGet() method.
Now inside the doGet() method use the getWriter() method of the response object and its returns the PrintWriter object,
which helps us to write on the browser. To get the number of rows from the database table there is a need for the connection between the database and the java program.
After the establishment of the connection with the database, fire a query for selecting the number of rows from the database table inside the executeQuery() method of the
PreparedStatement object and returns the ResultSet object. Now we have the ResultSet object, by the help of this object we can get the number of rows we have in the database table.
The number of rows we have in the database table will be displayed on the browser by the PrintWriter object.

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

public class ServletGettingNoOfRows extends HttpServlet{
  public void doGet(HttpServletRequest request, 
  HttpServletResponse response) throws 
  ServletException, IOException{
  int rows=0;
  response.setContentType("text/html");
  PrintWriter pw = response.getWriter();
  String connectionURL = "jdbc:mysql://localhost/zulfiqar";
  Connection connection;
  try{
  Class.forName("org.gjt.mm.mysql.Driver");
  connection = DriverManager.getConnection
   (connectionURL, "root", "admin");
  PreparedStatement pst = connection.prepareStatement("");
  ResultSet rs = pst.executeQuery
   ("select count(*) from emp_sal");
  while (rs.next()){
  rows = rs.getInt(1);
  }
  pw.println("The number of rows are " + rows);
  }
  catch(Exception e){
  pw.println("The exception is " + e);
  }
  }
}
  
web.XML

<web-app>
 <servlet>
 <servlet-name>santosh</servlet-name>
 <servlet-class>ServletGettingNoOfRows</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>santosh</servlet-name>
 <url-pattern>/ServletGettingNoOfRows</url-pattern>
 </servlet-mapping>
</web-app>

Read more...

How to get number of columns ina table using Servlets?

Consider a situation where there is a need to know about the number of columns in the table without touching our database.
As we are the programmers so why we should worry about the database.
We want to do the manipulation by sitting on our computer through our program without going into the database.
In this example we are going to exactly the same as we said above.
To make this possible we need to make a class named ServletGettingNoOfColumns,  the name of the program should be such that if in future there is any need to make any change in the program,
you can easily understand in which program you have to make a change.
As we know that in Servlet the main logic of the program is written inside the service method and in turn the service method calls the doGet() method.
Now inside the doGet() method use the getWriter() method of the response object and its returns the PrintWriter object,
which helps us to write on the browser. To get the number of columns from the database table there is a need for the connection
between the database and the java program.  After the establishment of the connection with the database,
pass a query for retrieving all the records from the database and this will return the PreparedStatement object.
To get the number of columns from the database we firstly need a reference of ResultSetMetaData object and we will get it only when if we have the ResultSet object
with us. To get the object of the ResultSet we will call the method executeQuery() of the PreparedStatement interface.
Now we have the object of the ResultSet. By the help of the ResultSet we can get the object of ResultSetMetaData.
We will get it by calling the method getMetaData() of the ResultSet interface.
The number of columns in the databasd table will be retrieved by the method getColumnsCount() of the ResultSetMetaData interface.
This method will return the integer type of value. The number of columns will be displayed on the browser by the PrintWriter object.

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

public class ServletGettingNoOfColumns 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("com.mysql.jdbc.Driver").newInstance();
  connection = DriverManager.getConnection(connectionURL, 
  "root", "admin");
  PreparedStatement pst = connection.prepareStatement(
  "select * from emp_details");
  ResultSet rs = pst.executeQuery();
  ResultSetMetaData rsmd = rs.getMetaData();
  int noOfColumns = rsmd.getColumnCount();
  //It shows the number of columns
  pw.println("The number of columns are " + noOfColumns);
  }
  catch(Exception e){
  pw.println("The exception is " + e);
  }
  }
}
web.xml

<web-app>
 <servlet>
 <servlet-name>Zulfiqar</servlet-name>
 <servlet-class>ServletGettingNoOfColumns</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>Zulfiqar</servlet-name>
 <url-pattern>/ServletGettingNoOfColumns</url-pattern>
 </servlet-mapping>
</web-app>

Read more...

How to get the column names from DataBase using Servlets?

Consider a situation where there is a need to know about the name of the columns without touching our database.
As we are the programmers so why we need to worry about the database.
We want to do the manipulation by sitting on our computer through our program without going into the database.
In this example we are going to exactly the same as we said above.
To make this possible we need to make a class named ServletGettingColumnsNames, the name of the program should be such that if in
future there is any need to make any change in the program, you can easily understand in which program you have to make a change.
Now inside the doGet() method use the getWriter() method of the response object and its returns the PrintWriter object,
which helps us to write on the browser. To get a column names from the database there is a need for the connection between the database
and the java program. After the establishment of the connection with the database pass a query for retrieving all the records from the
database and this will return the PreparedStatement object. To get the column names from the database we firstly need a reference of ResultSetMetaData object
and we will get it only when if we have the ResultSet object. To get the object of the ResultSet we will call the method executeQuery()
of the PreparedStatement interface. Now we have the object of the ResultSet. By the help of the ResultSet we can get the object of ResultSetMetaData.
We will get it by calling the method getMetaData() of the ResultSet interface.
The names of the columns will be retrieved by the method getColumnsNames() of the ResultSetMetaData interface.
The output will be displayed to you by the PrintWriter object.

ServletGettingColumnsNames class :
web.XML


Zulfiqar
ServletGettingColumnsNames


Zulfiqar
/ServletGettingColumnsNames













Read more...

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...

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