Wednesday, January 18, 2012

Sowmya, Chandra Batch-1

Understanding the structure of web applications

Web Applications use a standard directory structure defined in the Servlet specification. When developing web applications on J2EE platform, you must follow this structure so that application can be deployed in any J2EE compliant web server. (Tomcat, Weblogic, Jboss, websphere etc.. )
A web application has the directory structureas shown in below figure.

J2EE Web Application Directory Structure
The root directory of the application is called the document root. Root directory is mapped to the context path. Root directory contains a directory named WEB-INF. Anything under the root directory excepting the WEB-INF directory is publically available, and can be accessed by URL from browser. WEB-INF directory is a private area of the web application, any files under WEB-INF directory cannot be accessed directly from browser by specifying the URL like http://somesite/WEB-INF/someresource.html. Web container will not serve the content of this directory. However the content of the WEB-INF directory is accessible by the classes within the application. So if there are any resources like JSPs or HTML document that you don’t wish to be accessible directly from web browser, you should place it under WEB-INF directory.

WEB-INF directory structure

WEB-INF directory contains
  • WEB-INF/web.xml deployment descriptor
  • WEB-INF/classes directory  --> all class files unders this folder loaded by tomcat sercer to memory
  • WEB-INF/lib directory

/WEB-INF/web.xml

web.xml is called the web application deployment descriptor. This is a XML file that defines servlets, servlet mappings, listeners, filters, welcome files etc. Deployment descriptor is a heart of any J2EE web application, so every web application must have a web.xml deployment descriptor directly under WEB-INF folder.

/WEB-INF/classes

The classes directory is used to store compiled servlet and other classes of the application. If your classes are organized into packages, the directory structure must be reflected directly under WEB-INF/classes directory. The classes directory is automatically included in CLASSPATH.

/WEB-INF/lib

Lib directory is used to store the jar files. If application has any bundled jar files, or if application uses any third party libraries such as log4j, JDBC drivers which is packaged in jar file, than these jar files should be placed in lib directory.
All unpacked classes and resources in the /WEB-INF/classes directory, plus classes and resources in JAR files under the /WEB-INF/lib directory are included in classpath and made visible to the containing web application.
There are many changes in Servlet 3.0 Specification, web.xml file is optional, servlets, listeners and filters are no longer required to be defined in web.xml, instead they can declared using annotations. web.xml file can be devided into multiple files called webfragments.
Note Directory and file names are case sensitive.
Simple Servlet example

  1. How to write the servlet class.
  2. How to compile the Servlet class
First of all we need to create the directory structure for our sample web application as explained in the above tutorial. Create the directory structure as shown in below figure.




package jsptube.tutorials.servletexample;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WelcomeServlet extends HttpServlet {

@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

System.out.println("This is the frist Servlet ");


}


public void destroy() {

}
}

Now compile the servlet class as explained below.
Open the command prompt and change the directory to the servlet-example/WEB-INF/src/jsptub/tutorials/servletexample directory. Compile the WelcomeServlet.java using the following command. javac WelcomeServlet.java It will create the file WelcomeServlet.class in the same directory. Copy the class file to classes directory. All the Servlets and other classes used in a web application must be kept under WEB-INF/classes directory.
Note: to compile a servlet you need to have servlet-api.jar file in the class path.
The deployment descriptor (web.xml) file.
Copy the following code into web.xml file and save it directly under servlet-example/WEB-INF directory.

<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 
 <servlet>
  <servlet-name>WelcomeServlet</servlet-name>
  <servlet-class>jsptube.tutorials.servletexample.WelcomeServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>WelcomeServlet</servlet-name>
  <url-pattern>/WelcomeServlet</url-pattern>
 </servlet-mapping>
 <welcome-file-list>
  <welcome-file> /pages/form.html </welcome-file>
 </welcome-file-list>
</web-app>

Our sample application can be accessed at http://localhost:8080/Servlet-example/WelcomeServlet. If tomcat server is running on port other than 8080 than you need to change the URL accordingly.

Access the servlet from the HTML form SUBMIT button also.

write index.html as below

<html>
<body>
<form action="./WelcomeServlet" >

<input type="submit" value="Click me" />

</form>
</body>

1. open the index.html from the browser  ervlet-example/http://localhost:8080/Servlet-example/index.htmlindex.html
2. click on the Button, we will see that Servlet gets executed.
3. Tomcat console displasys the SOP that we have implemented in the doGET method.

Monday, December 19, 2011

How do I configure Weblogic Application server to connect to Postgres?

How do I connect to a Postgresql database from within an EJB using Weblogic server?
For some reason I spent many hours failing to get this to work before I finally cracked it. Here are the notes I made when I succeeded.
  1. The driver classes (postgresql.jar file) must be on the server CLASSPATH.
    For example, copy it to the WLHOME/ext directory, and edit the script WLHOME/config/mydomain/startWebLogic.cmd
    Append "./ext/postgresql.jar" to the CLASSPATH setting there.
  2. Start the WebLogic server for your domain.
  3. Create a JDBC Connection Pool which connects to the Postgres database, either by:
    1. ) Using the administrative console:
       - Configure a new JDBC Connection Pool
           - General tab:
        - Name: Any name you like for your pool (eg MyPoolName)
        - URL: jdbc:postgresql://hostname:port/database
          eg jdbc:postgresql://smirnoff.uk.ingenotech.com:5432/homepages
        - Driver Classname: org.postgresql.Driver
        - Properties: user=ed password=anything
        - ACL Name: (blank)
        - Password: The real password to connect to the database, this
                    will be kept encrypted and substituted for the value 
                    you put in "Properties".
              - Press "Create" 
          - Go to the "Targets" tab
              - Select "myserver" from the "Abailable" list and move it
                to "Chosen".  Apply.
        - Create a JDBC Data Source which references the Connection Pool above
          - Configure a new JDBC Data Source - Configuration Tab
            - Name: Any name you like (eg MyDataSource)
            - JNDI Name:  Make this the same as "Name" above (MyDataSource).
            - Pool Name: The name of the ConnectionPool created above (MyPoolName)
            - Press "Create" 
          - Go to the "Targets" tab
            - Select "myserver" from the "Available" list and move it
              to "Chosen".  Apply.
      

    2. ) or by using the command line as follows:
        java -cp {path to weblogic.jar} weblogic.Admin -url localhost:7001 \
             -username system -password password \
             CREATE_POOL .... TBD ....
      

    3. ) or, with the server stopped, edit the WLHOME/config/mydomain/config.xml file:
        - Add the following to create a connection pool:
          <JDBCConnectionPool DriverName="org.postgresql.Driver"
                                 MaxCapacity="10" 
                                 Name="MyPoolName"
                                 Password="{3DES}yIsebsUSRdE="
                                 Properties="user=ed;password=secret" 
                                 Targets="myserver"
                                 URL="jdbc:postgresql://hostname:port/database"/>
      
        - Add the following to create a Data Source referencing that pool:
          <JDBCDataSource JNDIName="MyDataSource" 
                             Name="MyDataSource" 
                             PoolName="MyPoolName" 
                             Targets="myserver"/>
      

  4. Define a reference to your Data Source in the EJB deployment descriptor files:
    In ejb-jar.xml within the section add:
    <resource-ref>
     <res-ref-name>jdbc/MyPoolName</res-ref-name> <!-- This is the name chosen for the Connection Pool with "jdbc/" prepended -->
     <res-type>javax.sql.DataSource</res-type>
            <res-auth>Container</res-auth>
          </resource-ref>
    

    In weblogic-ejb-jar.xml within the <weblogic-enterprise-bean> section add:
    <reference-descriptor>
          <resource-description>
            <res-ref-name>jdbc/MyPoolName</res-ref-name> <!-- This is the name chosen for the Connection Pool with "jdbc/" prepended -->
     <jndi-name>MyDataSource</jndi-name> <!-- this is the name you chose for the DataSource -->
          </resource-description>
        </reference-descriptor>
    
  5. In your bean or a suitable utility class, write a "getConnection()" method which returns a Connection object which you can then use in the usual way. This will do a JNDI lookup to find a javax.sql.DataSource object configured in your server and obtain a Connection from that. The name used to obtain your DataSource is, confusingly, not the JNDI name but the set above, beneath the java:comp/env hierarchy as follows:
    private Connection getConnection() throws NamingException
    {
        InitialContext ic = new InitialContext();
        DataSource ds = (DataSource)ic.lookup("java:comp/env/jdbc/MyPoolName");
        return ds.getConnection();
    }
    
  6. Here is an example of how to use your Connection "in the usual way"...
    Connection conn = null;
    PreparedStatement st = null;
    try
    {
        conn = getConnection();
        // Prepare your SQL statement, substitute "somevalue" for the first "?" parameter.
        st = conn.prepareStatement("SELECT COL1, COL2, COL3 FROM TABLENAME WHERE COL1 = ?");
        st.setString(1, somevalue);
    
        // Execute the SQL and read the rows returned
        ResultSet rs = st.executeQuery();
        while (rs.next())
        { // Read and process each row of the ResultSet
     String col1 = rs.getString(1);
     String col2 = rs.getString(2);
     String col3 = rs.getString(3);
     // etc...
        }
    }
    catch (SQLException ex)
    {
        System.out.println("SQL exception occurred" +ex);
    }
    finally
    {
        try
        {
     if (st != null)
         st.close();
        }
        catch (SQLException ex)
        {
        }
    
        try
        {
     if (conn != null)
         conn.close();
        }
        catch (SQLException ex)
        {
        }
    }
    

Friday, December 9, 2011

Friday, September 16, 2011

J2EE Course Content

Discussion would always 
go beyond these topics
and covers Practical Problems and Solutions in Real Time IT industry.