RSS

Monthly Archives: April 2013

BOOK Java Script (Ivan Bayross)

“Web Enabled Commercial Application Development Using HTML, DHTML, PERL, Java Script” Download

 
Leave a comment

Posted by on April 30, 2013 in Books

 

Create a servlet filter that logs all access to and from servlets in an application and prints the following to System.out: a. the time the request was received b. the time the response was sent c. how much time it took to process the request d. the URL of the resource requested e. the IP address of the visitor

ex22.java

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

public class ex22 implements Filter
{
          ServletContext context;
          public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) throws IOException,ServletException
          {
                   HttpServletRequest request=(HttpServletRequest)req;
                   PrintWriter out=res.getWriter();
				   
                   Date myreqdate=new Date();
                   System.out.println("request received on "+myreqdate);
				   
		   // Note the start time.
		   long startTime = System.currentTimeMillis();

                   String mylog=new String(request.getRemoteHost()+"tried to access"+request.getRequestURL()+"on Time"+new Date());
	           context.log(mylog);
                   
		    chain.doFilter(req,res);
				   
	            //Note the end time.
		    long endTime = System.currentTimeMillis();
                   
                   Date myresdate=new Date();
                   context.log("Response receive on"+myresdate);
                  
                   long diff =endTime-startTime;
		   context.log("Start time : " + startTime);
		   context.log("End time: " + endTime);
                   context.log("Time take to process the request is "+diff);
          }
          public void init(FilterConfig confy)
          {
                   context=confy.getServletContext();
          }
          public void destroy()
          {
          }
}

Apply these filter to servlet file.

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
                          
public class FilterEx extends HttpServlet 
{
	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
	{
		PrintWriter out = res.getWriter();
		res.setContentType("text/html");
		out.println("Testing");
		  try
                   {
                             Thread.sleep(1000);
                   }
                   catch(Exception e)
                   {
                             out.println(e);
                   }
	}
}

web.xml

<servlet>
    <servlet-name>FilterEx</servlet-name>
    <servlet-class>FilterEx</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>FilterEx</servlet-name>
      <url-pattern>/FilterEx</url-pattern>
  </servlet-mapping>
  <filter>
    <filter-name>ex22</filter-name>
    <filter-class>ex22</filter-class>
	</filter>
    <filter-mapping>
    <filter-name>ex22</filter-name>
    <servlet-name>FilterEx</servlet-name>
  </filter-mapping>
 
Leave a comment

Posted by on April 25, 2013 in Example

 

Write a code in JDBC where a maximum limit of database connections has been reached?

Use DatabaseMetaData.getMaxConnections() and compare to the number of connections currently open. Note that a return value of zero can mean unlimited

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;

public class Main {
  private static final String DRIVER = "com.mysql.jdbc.Driver";
  private static final String URL = "jdbc:mysql://localhost/yourDatabase";
  private static final String USERNAME = "root";
  private static final String PASSWORD = "";
  public static void main(String[] args) throws Exception {

    Class.forName(DRIVER);
    Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
    DatabaseMetaData metadata = connection.getMetaData();

    int maxConnection = metadata.getMaxConnections();
    System.out.println("Maximum Connection = " + maxConnection);
    connection.close();
  }
}
 
 
Leave a comment

Posted by on April 25, 2013 in Example

 

JDBC Transaction

JDBCTransaction.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import  java.sql.*;
public class JDBCTransaction extends HttpServlet 
{
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        Connection connection = null;
        Statement statement = null;
        
        try {
           Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
	   connection=DriverManager.getConnection("jdbc:odbc:studentora","scott","tiger"); 
            
            //Here we set auto commit to false so no changes will take
            //effect immediately.
            connection.setAutoCommit(false);
            
            statement = connection.createStatement();
            
            //Execute the queries
            statement.executeUpdate("UPDATE stud SET name='abc' WHERE rollno = 2");
                      
            //No changes has been made in the database yet, so now we will commit
            //the changes.
            connection.commit();
        } 
	catch (ClassNotFoundException ex) 
        {
            ex.printStackTrace();
        }
	catch (SQLException ex) 
	{
            ex.printStackTrace();
            try
            {
                //An error occured so we rollback the changes.
                connection.rollback();
            } 
	    catch (SQLException ex1) 
	    {
                ex1.printStackTrace();
            }
         }  
	 finally 
	 {
            try
	    {
                if (statement != null)
                    statement.close();
                if (connection != null)
                    connection.close();
            }
	    catch (SQLException ex) 
	    {
                ex.printStackTrace();
            }
        }
        
    }
}
 
Leave a comment

Posted by on April 22, 2013 in Example

 

Pass the initialization parameter to JSP Page

web.xml

 <servlet>
        <servlet-name>InitPage</servlet-name>
        <jsp-file>/InitPage.jsp</jsp-file>
        <init-param>
           <param-name>firstName</param-name>
           <param-value>abc</param-value>
        </init-param>
</servlet>

<servlet-mapping>
     <servlet-name>InitPage</servlet-name> 
     <url-pattern>/InitPage</url-pattern> 
 </servlet-mapping>

InitPage.jsp

<HTML>
<HEAD><TITLE>JSP Init Test</TITLE></HEAD>
<BODY BGCOLOR="#FDF5E6">
<H2>Init Parameters:</H2>
<UL>
<LI>First name: <%= firstName %>
</UL>
</BODY></HTML>
<%!
private String firstName = "First name is missing.";

public void jspInit() 
{
ServletConfig config = getServletConfig();
if (config.getInitParameter("firstName") != null) 
{
firstName = config.getInitParameter("firstName");
}
}
%>
 
Leave a comment

Posted by on April 22, 2013 in Example

 

Callable Statement

CallableStatemnet Download

 
Leave a comment

Posted by on April 22, 2013 in Material

 

Example of callablestatement with function

To create the function follow these syntax:
create or replace function incr(rln IN number) RETURN number is
begin
update stud set name=’mno’ where rollno=rln;
return ( SQL%ROWCOUNT);
END incr;

callablestatement3.java

import java.sql.*;

class callablestatement3
{
	public static void main(String args[])
	{
		Connection con;
		CallableStatement cs;
		

		try
		{

		Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
	    con=DriverManager.getConnection("jdbc:odbc:studentora","scott","tiger"); 

			cs=con.prepareCall("{?=call incr(?)}");
			cs.registerOutParameter(1,Types.INTEGER);
			cs.setInt(2,1);
			cs.execute();
   		    System.out.println("Rows : "+cs.getInt(1));
			con.close();
		}
		catch(ClassNotFoundException e)
		{
			System.out.println(e);
		}
		catch(SQLException e)
		{
			System.out.println(e);
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
	}	
}
 
Leave a comment

Posted by on April 22, 2013 in Example

 

Example of Callable Statement with input and output parameter

//procedure with input and output parameter
create or replace procedure test(roll IN number,nm OUT varchar) as
begin
select name into nm from stud where rollno=roll;
end;
/
callablestatement1.java

import java.sql.*;

class callablestatement1
{
	public static void main(String args[])
	{
		Connection con;
		CallableStatement cs;
		try
		{
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
	     	con=DriverManager.getConnection("jdbc:odbc:studentora","scott","tiger");
			cs=con.prepareCall("{call test(?,?)}");
			cs.registerOutParameter(2,Types.VARCHAR);
			cs.setInt(1,1);
			cs.execute();
			String nm=cs.getString(2);
			System.out.println("Name="+nm);
     		con.close();
		}
		catch(ClassNotFoundException e)
		{
			System.out.println(e);
		}
		catch(SQLException e)
		{
			System.out.println(e);
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
	}	
}
 
Leave a comment

Posted by on April 22, 2013 in Example

 

Example of Callable Statement

To Run following example follow the stpes.

Step 1: create a DSN
(Control Panel -> Administrative Tools -> Data Sources (ODBC) -> Add User DSN -> provide the name of DSN, username and server name (For example : DSN NAME : studora, username: scott , server name : localhost) )

Step 2: create a procedure named remove like these

create table stud (rollno number,name varchar2(15),city varchar2(25));

insert into stud values(1,’abc’,’rajkot’);

create or replace procedure remove (name1 varchar2) as
begin
delete from stud where name=name1;
end;
/
//To execute the procedure from sql prompt :
execute remove(‘abc’);

step 3 :

import java.sql.*;
class callablestatement
{
	public static void main(String args[])
	{
		Connection con;
		CallableStatement cs;
		try
		{
		        //with DSN
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                       // provide the username and password
	     	con=DriverManager.getConnection("jdbc:odbc:studentora","scott","tiger");
			cs=con.prepareCall("{call remove(?)}");
			cs.setString(1,"abc");
			cs.executeUpdate();
			System.out.println("Record deleted");
			cs.close();
			con.commit();
			con.close();
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
	}
}
 
Leave a comment

Posted by on April 22, 2013 in Example

 

Deployment Descriptor file (web.xml)

Deployment Descriptor File Download

 
Leave a comment

Posted by on April 19, 2013 in Material