java4all@1986 java. Powered by Blogger.

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

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