Showing posts with label J2EE. Show all posts
Showing posts with label J2EE. Show all posts

Monday, June 24, 2013

JDBC 7 STEPS :

Seven Steps to JDBC
      The java program can access the database using JDBC. the seven steps that are needed to access database are
1.    Import the package
2.    Load and register the driver
3.    Establish the Connection
4.    Create a Statement object
5.    Execute a query
6.    Process the result
7.    Close the connection
Step1: Import java.sql package
          The important classes and interfaces of JDBC are available in the java.sql package . So inorder to access the databases it must be imported in our application.
 import java.sql.*;
Step 2: Loading and registering the driver
           In order to access database it must have the particular driver for that database. In Java we have to inform the Drive Manager about the required driver this is done with the help of the method forName(String str) available in  the class named Class
Class.forName(“path with driver name”);
          In an application the user can register more than one driver. The statement used to load and register the JDBC-ODBC bridge driver is
                    Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Step 3: Establishing the connection
           Establishing connection means making a connection to access RDBMS through JDBC driver. The connection can be established with the help of getConnection() method available in DriverManager class. The established connection is then set to new connection object.
Connection cn=DriverManager.getConnetion (“jdbc:odbc:DSN”, ”administrator”, “password”);
            Where DSN-Data Source Name
  When the statement is executed the connection is set to the Connection object cn. For example to connect the ODBC data source named mydata via JDBC –ODBC bridge the statement is
          Connection cn= DriverManager.getConnection (“jdbc:odbc:mydata”);
Step 4: Creating the statement
        A Statement object is used for executing a static SQL statement and obtaining the results produced by it. The createStatement() method is used to create statements using the established connection.
The methods used for creating the statements are
·         Statement createStatement()
Returns a new Statement object.Used for general queries
·         PreparedStatement prepareStatement(String sql)
Returns a new PreparedStatement object.For a statement called multiple times with different values (precompiled to reduce parsing time)
·         CallableStatement prepareCall(String sql)
Returns a new CallableStatement object for stored procedures
Step 5: Executing the Query
          After making connection to the database we are ready to execute the SQL statements. The  various methods available in Statement object to execute the query are
·         ResultSet executeQuery(String)
           Execute a SQL statement that returns a single ResultSet. After executing the SQL statements the requested data is stored in the ResultSet object.
·         int executeUpdate(String)
          Execute a SQL INSERT, UPDATE or DELETE statement. Returns the number of rows changed.
·         boolean execute(String)
           Execute a SQL statement that may return multiple results.
Step 6: Retrieving the result.
          A ResultSet provides access to a table of data generated by executing a Statement.Only one ResultSet per Statement can be open at once.The table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. The 'next' method moves the cursor to the next row.
Methods:
·         public boolean first()
Moves the cursor to the first row in this ResultSet object.
·         public boolean last()
Moves the cursor to the last row in this ResultSet object.
·         public boolean next()
Moves the cursor down one row from its current position.
The methods used to retrieve the values from the current row
·         Type getType(int columnIndex)
Returns the given field as the given type. Fields indexed starting at 1 (not 0)
·         Type getType(String columnName)
Returns the data at the specified column
In the above methods the Type should be replaced by the valid datatypes such as Boolean, String, Int, Long, Float etc as getString(Column name), getInt(column index) etc.
Step 7: Closing the connection and statement
          When the client request is completed we have to close the created objects of Connection and Statement using close() method.
st.close();
cn.close();


Monday, June 18, 2012

Spring Ioc Types


Spring Ioc Types

Spring Ioc Types

Generally we have two types of IOC styles.
               
               1.Dependency lookup
               2.Dependency  injection

1.Dependency Lookup:
With dependency lookup your component is responsible to get the dependency component.
Dependency lookup
We have two types of lookup dependency mechanisms they are:
1.1. Dependency pull (DP).
1.2. Contextualized Dependency Lookup (CDL)

1.1. Dependency Pull:
In Dependency pull component will get the other dependent from a centralized registry like JNDI.

1.2 Contextualized Dependency Lookup:
Contextualized dependency lookup is similar to dependency pull, but objects will be taken from container instead of taking from centralized registry

2. Dependency Injection:
With dependency injection spring IOC container automatically injects the dependencies into the components.
Dependency Injection
 We can implement the dependency IOC in three ways.


            1. Constructor-Injection
            2. Setter-Injection
            3. Getter-Injection

1. Constructor-Injection:
In this spring container injects the dependencies through constructor.
public class B
{
        --------
        --------
        --------
}
 
public class C
{
        --------
        --------
        --------
}
 
public class A
{
        private C cobj;
        private B bobj;
        
        public A(C cobj, B bobj)
        {
               this.bobj=bobj;
               this.cobj=cobj;
        }
}


context.xml

<beans>
<bean id="cobj" class="com.javayom.C"/>
<bean id="bobj" class="com.javayom.B"/>
<bean id="aobj" class="com.javayom.A">
<constructor-arg index="1">
<ref bean="bobj" />
</constructor-arg>
<constructor-arg index="0">
<ref bean="cobj" />
</constructor-arg>
</bean>
</beans>

1. Setter-Injection:
In this bean dependencies will be injected into the component through java bean style setter method.
public class B
{
        --------
        --------
        --------
}
 
public class C
{
        --------
        --------
        --------
}
 
public class A
{
        private C cobj;
        private B bobj;
        
        public void setCobj(C cobj)
        {
               this.cobj=cobj;
        }
        public void setBobj (B bobj)
        {
               this.bobj=bobj;
        }
 
}


context.xml
 
<beans>
<bean id="cobj" class="com.javayom.C"/>
<bean id="bobj" class="com.javayom.B"/>
<bean id="aobj" class="com.javayom.A">
<property name="cobj">
<ref bean="cobj"/>
</property>
<property name="bobj">
<ref bean="bobj"/>
</property>
</bean>
</beans>

3. Getter-Injection:

public class B
{
        --------
        --------
        --------
}
 
public class C
{
        --------
        --------
        --------
}
 
 
abstract public class A
{
        abstract public B getBobj ();
}


context.xml
     
<beans>
<bean id="cobj" class="com.javayom.C"/>
<bean id="bobj" class="com.javayom.B"/>
<bean id="aobj" class="com.javayom.A">
<lookup-method name="getBobj" bean="bobj"/>
</bean>
</beans> 

JSP'S Scripting Elements


JSP'S Scripting Elements

JSP'S Scripting Elements


There are 3 types of Scripting elements in JSP

1. Scriptlets
2. Expressions
3. Declarations

1.Scriptlets (<%?any java Statements?.%>) : -

Inside a scriptlet, we can write any valid java statements and all the statements must be terminated with " ;"
All the java statements inside the scriptlet will be placed inside _jspService().

Example: -

<%
out.println("JAVAYOM");
int x=10,y=20;
%>
Expressions (<%=any expression%>): - 

Expression is a shortcut form of out.println( ). All the expressions will be placed inside _jspService( ).
Don't use the semicolon at the end of the expression.
Don't include the expressions inside the scriptlet.

Example: -

<%= " JAVAYOM " %>

Declarations (<%!any declarations%>): -

Declarations are used to declare variables and methods.
Contents of declaration section will be placed outside _jspService( ) and inside servlet class.

Example: -

<%!
int a=99;
void m1( )
{
}
%>
Note: Don't write these 3 elements one in another, which gives compilation error.

Example: -

Hai.jsp

<html>
<body>
<%=" JAVAYOM "%>
<%
out.println("JAVAYOM ");
int x=10,y=20;
%>
<%!
int a=99;
void m1()
{
}
%>

This JSP when converted into java class it is as follows: -

class hai_jsp extends HttpJspBase
{
int a=99;
void m1()
{
}
_jspService(-,-)
{
out.write("<html>/r/n<body>");
out.println("javayom");
out.print("javayom");
int x=20,y=20;
out.write("</body>/r/n</html>");
}
}
But user can override init () and destroy () methods inside declarations.

Servlets

Servlets

SERVLETS

Introduction :
Client Server Application
Web-Based Application
1. In this we have to divide the application into 2 parts,one part we have to install in server machine and another part in client machine.

2. When you modify the application you have to re-install the client software in all the client machines.

3. We can use C, C++, java etc to develop client server application.


4. There is a limit for client server application in terms of accessibility.
1. We can place the entire application in the server itself and access this application with the help of web browser.

2. When you modify the application no modification in the client machines.


3. We can use servlets, JSP, ASP, PHP, Perl Script etc. to develop the web application.

4. It is unlimited(accessibility of the users)


Web Clients :

1. Internet Explorer
2. Netscape Navigator
3. Opera
4. Mozilla

Web Servers :

1. Tomcat
2. Any Application Servers

Technologies :

1. JSP
2. Servlets
3. PHP
4. ASP
5. Perl Script

Application Servers :

1. Web logic
2. JBoss
3. JRun
4. Oracle 9i
5. Web Sphere
6. E-matrix
7. Pramathi
Steps to Install Tomcat

1. Make sure that j2sdk is installed in your machine and paths and classpath are set and is running properly.
2. Double click on Jakarta-tomcat-5.0.16.
3. Click on next.
4. Click on I Agree.
5. Click on next.
6. Change the destination folder to d:\tomcat5.0 and click on next.
7. Change the port number to 9999, give username and password and click on next.
8. Click on install.
9. Uncheck two options and click on finish.
10. Start the server and open the browser and type the following http://localhost:9999.

Simple example of Html :

<html>
<head></head>
<body>
<font color="red">
<h1> Welcome to Javayom.blogspot.com </h1>
</font>
</body>
</html>

The above file consists of a Html code with simple welcome note. You have just type the above thing in notepad and save it as a .html. Then using one of the
browser in your system just open that?.

Program Trace :

<html> : used for starting and ending of a html file.
<head> : used for starting and ending of a header in the html file.
It consists of different types of tags such has
<body> : used for starting and ending of body in the html file. All the coding part will be available here only..
<h1> : used for making the heading of the thing.
<font> : used for formatting the text with different things such as color, size etc.
Difference between Web-Server and Application-Server
Client Server Application
Web-Based Application
1. Web Server has web container which gives the support for web components called "servlets" & "jsp"


2. Examples of Web Servers :
° Apache Tomcat
° Java Web Server
° Roxen Web Server
° Zeus WebServer






3. Services of Web container :
° Networking
° Threading
° Streams
° Declarative Security
° JSP Support
° Resource Management
1. Application Server as 2 categories, one is web container and another is EJB container. Web container supports JSP and servlets & EJB container supports EJB components.

2. Examples of Application Server :
° Web logic
° Web Sphere
° JBoss
° JRun
° Oracle 9i
° Resin
° Orien
° Pramathi
° E-matrix etc

3. Services of EJB container :
° Networking
° Threading
° Streams
° Resource Management
° Transaction Management
° Security
° Persistence
° Timer Service
° Web Services
Directory structure of Web-application

Note : One and only one instance will be created for each servlet because servlets are following Singleton Design Pattern.

» Servlet interface is the root for all the servlets.
» Each servlet class should implement Servlet interface directly or indirectly.
» Sun has given servlet classes one is GenericServlet and second is HttpServlet.
» GenericServlet is direct sub-class of Servlet interface
& is implementing all the methods of Servlet interface except service 
(ServletRequest,ServletResponse) method.
» GenericServlet is protocol independent (i.e. we can use any protocol)
to send the request.
» HttpServlet is sub-class of GenericServlet & is implementing abstract
service(ServletRequest, ServletResponse) method in GenericServlet.
» HttpServlet has two service() methods, one is with pubic specifier &
is taking ServletRequest & ServletResponse as parameters, second with 
protected HttpServletRequest & HttpServletResponse as parameters.
» In addition to these 2 service () methods HttpServlet has 7 protected 
doXXX() methods with HttpServletRequest & HttpServletResponse
as parameters :
o doGet(HttpServletRequest, HttpServletResponse)
o doPost(HttpServletRequest, HttpServletResponse)
o doHead(HttpServletRequest, HttpServletResponse)
o doPut(HttpServletRequest, HttpServletResponse)
o doDelete(HttpServletRequest, HttpServletResponse)
o doTrace(HttpServletRequest, HttpServletResponse)
o doOptions(HttpServletRequest, HttpServletResponse)
» The above 7 are Http methods used to send the request from client.
» The following is the way to specify the http method :
    <form action="/login. do" method="post">
    </form>
» The default method is get().

Second Servlet Example :

1.) second.html
<html>
   <body>
    <center>
    <font size=6 color=red face="monotype corsiva">

</font><br><br>
     <form action="/yom.do" method="get">
         <input type="text" name="fname">
         <input type="text" name="lname">
         <input type="text" name="email">
         <input type="submit" value="Show">
     </form>
   </body>
</html>



2.)   MyServlet2.java 
package com.javayom.servlets;
 
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet2 extends HttpServlet
{
  String fn,ln,em;
  public void service(HttpServletRequest req,

      HttpServletResponse res)
            throws IOException,ServletException{
  fn=req.getParameter("fname");
  ln=req.getParameter("lname");
  em=req.getParameter("email");
  res.setContentType("text/html");
  PrintWriter out=res.getWriter();
  out.println("<h2>Hi.."+fn+" "+ln);
  out.println("<h2>Your email is"+em);
  Enumeration e=req.getHeaderNames();
  while(e.hasMoreElements())
  {
     String hn=e.nextElement().toString();
     out.println("<h3>"+hn);
     String hv=req.getHeader(hn);
     out.println("::"+hv);
  }
  out.println("<h3>Auth type"+req.getAuthType());
  out.println("<h3>Method"+req.getMethod());
  out.println("<h3>Remote User"+req.getRemoteUser());
  out.println("<h3>charEncoding."+

 req.getCharacterEncoding());
  out.println("<h3>Content-type"+req.getContentType());
  out.println("<h3>Contentlength"+

         req.getContentLength());
  out.println("<h3>servername"+req.getServerName());
  out.println("<h3>Protocal"+req.getProtocol());
  out.println("<h3>Serverport"+req.getServerPort());
  out.println("<h3>RemoteAddr"+req.getRemoteAddr());
  out.println("<h3>Remotehost"+req.getRemoteHost());
  out.println("<h3>Remoteport"+req.getRemotePort());
  out.println("<h3>local addr"+req.getLocalAddr());
  out.println("<h3>Local name"+req.getLocalName());
  out.println("<h3>Localport"+req.getLocalPort());
  out.println("<h3>is secure"+req.isSecure());
    Locale lc=req.getLocale();
  out.println("<h3>"+lc.getCountry());
  out.println("<h3>"+lc.getLanguage());
  out.println("<h3>"+lc.getVariant());
}
}



3.)   web.xml 
<web-app>
  <servlet>
        <servlet-name>myser</servlet-name>
        <servlet-class>com.javayom.servlets.MyServlet2

</servlet-class>
  </servlet>
  <servlet-mapping>
        <servlet-name>myser</servlet-name>
        <url-pattern>/yom.do</url-pattern>
  </servlet-mapping>
</web-app>
Basic flow of the Servlet

» In World Wide Web(www) we are using http protocol to send the request & receive the responses.
» Here we using web browse (application) to send the request to the web server & receive the response from web server.
» Web server is an application which is used to receive the requests from web-clients, upon processing the requests and
send the response to the web-client.
» Http protocol makes the communication between web-browser and web-server.
» The request we are sending using http protocol is called as Http-request
and is having 2 parts. One is called Http-request header and second is Http-request body.
» Response we are getting using http protocol is called Http-response and is having 2 parts. One is called Http-response
header and second is Http-response body.
» Http protocol is a stateless protocol, i.e. it doesn't maintain client's conversational state i.e. it won't remember what
happen in the pervious request.
» Http is build upon TCP\IP.
» TCP is responsible to control the transmission of data from one machine to other.
» IP is responsible to carry the data from one machine to other. 
Servlet Example

Files Required : 
1. first.html
2. FirstServlet.java
3. web.xml

1. first.html :
<html>
   <body>
      <center><br><br>
      <font color="red" size="5">

JavaYom

</font >
      <form action="/login.do">
          Enter Name :
          <input type="text" name="ur_name">
          <input type="submit" value="Submit">
      </form>
      </center>
   </body>
</html>
        
2. FirstServlet.java :
package com.javayom;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet
{
public void service(HttpServletRequest request, HttpServletResponse
response) throws IOException,
ServletException
{
//1.take the data
String username=request.getParameter("ur_name");
//2.process
username="Hello ! "+username+" Welcome to Servlet First Program?";
//3.send response back to client
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println(username);
out.close();
}
}
3. web.xml :
<web-app> 
   <servlet> 
     <servlet-name>first</servlet-name>        
     <servlet-class>

com.javayom.FirstServlet

</servlet-class> 
   </servlet>       
   <servlet-mapping>        
     <servlet-name>first</servlet-name>        
     <url-pattern>/login.do</url-pattern>      
   </servlet-mapping>       
<web-app> 
        
Steps to run the Servlet Program : 

1. Compile the servlet file :
a. Set the classpath for servlet-api.jar [ d:\tomcat5.0\common\lib\servlet-api.jar ]
b. javac -d . *.java

2. Deployment Steps :
a. Copy the first.html to webapps\ROOT\
b. Copy the "com" folder to ROOT\WEB-INF\classes\
c. Update the web.xml
d. Start the Tomcat server.
e. Open the internet explorer and type http://localhost:9999/first.html

Servlet can be referred by the container with 2 names :
a. Servlet-name (Used by container)
b. Servlet-class ( -do- )
c. Url-pattern (Used by user)
Servlet Life Cycle


Servlet have the following 3 life cycle methods :
1.init()
2.service()
3.destroy()

»Servlet life cycle management will be done by container.
»In servlet life container does the following things :
a. Creating the servlet instance.
b. Calling the life cycle methods.
c. Destroying the servlet instance.
»Init() method will be called by the container to initialize servlet instance, this will happen only once in servlet life.
»ervice() method will be called by the container to provide the service for the given request, this will be called "n" number of times based on the number of requests coming.

»Destroy() will be called by the container to destroy the instance.

When you send a request to the servlet first-time, the following steps will happen :
1.Container identify the servlet class for the given request with the help of url-pattern in web.xml.
2.If url-pattern found then servlet name will be taken
else
give an error back to client
3.With servlet-name container identifies the servlet-class.
4.Container search for servlet-class in WEB-INF \classes folder or its sub-folders if any package structure.
5.If servlet-class found
Load the class into the memory
else
give an error back to the client.
6.Create the Instance of servlet by calling default constructor.
7.Container creates ServletConfig object.
8.Container reads the init parameters specified in the web.xml and associates with the Config object & also associates context object which is created at server startup.
9.Container calls the init() method by passing ServletConfig as parameter.
10.Container creates a new thread or obtains thread from the pool.
11.Container creates HttpServletRequest , HttpServletResponse objects.
12. Container calls service(HttpServletRequest, HttpServletResponse) method by passing request & response as parameters.
13.Code inside the service method will be executed & response will be given to the client.

Second request onwards container will do the following things :
1. Container identify the servlet class for the given request with the help of url-pattern in web.xml If url-pattern found then
               servlet name will be taken
                       else
               give an error back to client
2. With servlet-name container identifies the servlet-class.
3. Container search for servlet-class in WEB-INF \classes folder or its sub-folders if any package structure.
4. If servlet-class found
            Load the class into the memory
                else
            give an error back to the client.
               
5. Container creates a thread or takes already created thread form the pool.
6. Container creates HttpServletRequest, HttpServletResponse objects.
7. Container calls service(HttpServletRequest, HttpServletResponse) method by passing request & response as parameters.
8. Code inside the service method will be executed & response will be given to the client.

Container Behavior when a servlet is called :
» Container always tries to call HttpServlets's public service() method.
» When your not overriding this in your servlet HttpServlet public service will be called.
» When your overriding this in your servlet, your's servlet's service() method with ServletRequest & ServletResponse will be called.
» Instead of overriding service(ServletRequest ,ServletResponse) in your servlet, when you override service(HttpServletRequest,HttpServletResponse),
container calls HttpServlet's public service method and that in turn calls your servlet's service(HttpServletRequest,HttpServletResponse) .
» Instead of overriding both the service methods when you override doXXX() methods, container calls HttpServlet's public service(), that in turn calls protected service() and that decides http method associated with the http request & invokes the doXXX() in your servlet.
» When the corresponding doXXX() method is not their an error page will be sent to the client with the status code - 405.