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.

JDBC Drivers


JDBC Drivers

Type1 Driver: jdbc-odbc bridge Driver:
ARCHITECTURE:
CLIENT SERVER


Fig. JDBC-ODBC Bridge Driver


Type1 driver translates jdbc call or request to Microsoft ODBC call or request (Open Database Connectivity). The converted ODBC request will interact with vendor specific client side database library.
The client side database library makes a call to database server which is the native Call or native request.
Note:
Name : jdbc-odbc bridge
Vendor : javasoft +intersolv
Path : none
Classpath : d:\j2sdk1.5\jre\lib\rt.jar
Classname : sun.jdbc.odbc.jdbcOdbcDriver
Url : jdbc:odbc:DSN name

Advantages:
1.When migrating from one platform to other platform then use existing ODBC Drivers and DSN name.
2.Suitable for small scale applications.

Disadvantages:
1.Type 1 Driver is limited for windows platform because of ODBC Driver.
2.When you are using Type1 lot of conversions has to be done because of this Request and response time will be more.
3.Performance of Type1 is less when compare with other drivers.
4.We have to install some database library in client machine also.
5.Type 1 is not suitable for Internet applications.
Type2 Driver: partial native partial java Driver
ARCHITECTURE
CLIENT SERVER
Fig. Type2 Driver Architecture
When you make a jdbc call, jdbc call will be converted to native call with the help of client side database library


Notes:
Name : partial native partial java Driver
Vendor : DB Vendor
Path : d:\oracle\ora90\bin;
Classpath : d:\oracle\ora90\jdbc\lib\classes111.jar
Classname : oracle.jdbc.driver.OracleDriver
Url : jdbc:oracle:oci8: @hostname:portnumber:SID

Example : jdbc:oracle:oci8: @hostname: 1521:SID

Advantages:
1. Performance of this driver is better than Type1.
2. It is compatible in all Operating System.

Disadvantages:
1. In this we have to install some of database library in client machine. Because of this maintenance will be increased.
2. It is not suitable for Internet applications.
Type3 Driver: Net protocol driver
ARCHITECTURE


CLIENT Middleware ServerDB Server
Fig. Type 3 Driver Architecture
When you make a jdbc call that will interact with the middleware server where the database library is available and this call will be converted to your native call using that library.

Notes:
Name : Net protocol driver
Vendor : intersolv
Software : install IDS Server
Path : d:\idsserver\idss.exe;
Classpath : d:\idsserver\idsdriver.jar
Classname : ids.driver.IdsDriver
Url : jdbc:ids://hostname//12/conn

Example : jdbc:oracle:oci8: @hostname: 1521:SID

Advantages:
1.No need to install DB Library
2.It is suitable for Internet applications.

Disadvantages:
1.Using this Type3 we donot have to chance to interact with DBServer directly. We have to go through the middleware server. This increases request and response time.
2. Performance is little bit poor than Type1 and Type2.
Type4 Driver: pure java driver
ARCHITECTURE
CLIENT SERVER
Fig. Type 4 Driver Architecture


When you want a jdbc call that will be converted to a native call directly.

Notes:
Name : pure java driver
Vendor : DB Vendor
Software : any oracle software
Path : d:\oracle\ora90\bin;
Classpath : d:\oracle\ora90\jdbc\lib\classes111.jar(Set classpath only on server systems)
Classname : oracle.jdbc.driver.OracleDriver
Url : jdbc:oracle:thin:@hostname:portnumber:SID

Example : jdbc:oracle:thin:@hostname: 1521:SID

Advantages:
1.No need to install DB Library in client machine.
2.It is suitable for Internet applications.
3.Performance of this driver is best among four JDBC Drivers.

Disadvantages:
1.Elapsed time (request time+processing time+response time) is little bit higher than Type2.

Comparison between Type2 and Type4:
1. Performance wise Type 4 is best whereas Speed wise Type2 is best.
2. Type2 is not good for stored procedures but good for prepared statements. Whereas Type4 is good for all.
3. Type2 is not portable on all Operating Systems whereas Type4 is portable.
4. Type2 is not good for internet applications whereas Type4 is good.
5. Type2 is not supported by all databases whereas Type4 supports all.