Java Servlets and J2EE

  

These are my personal notes that I use as a quick help in my work.
You are welcome to read them.

Contents of current page Top-level home page
 
Index  Java Internet Oracle Notes
Linux Basics Web Basics SQL Notes
Informatica Servlets Apache BkpRstore SQL*Plus
Teradata   LDAP Storage PL/SQL
Windows     Tables OEM
UML   Net8 Portal
SQL Server Python perl Performance OLAP
Vmware Visual Basic PHP/MySQL User Mgmt  
Git        
More technical pages here

Contents

 


Introduction

Servlet package description at http://java.sun.com/products/servlet/2.1/api/packages.html  
See Oracle 9iAS Containers for J2EE Services Guide

Servlets have no static main() method.

All servlets must implement the javax.servlet.Servlet interface. GenericServlet and HttpServlet implement this interface. The service method handles requests. The init method is called by the servlet container so that the servlet can initialize itself. The HttpServlet has additional methods such as doGet, doPost, doPut.

Some definitions:

JNDI
Java Naming and Directory Interface
RMI
Java Remote Method Invocation
JAAS
Java Authentication and Authorization Service
JTA
Java Transaction API
JMS
Java Message Service
JAF
JavaBeans Activation Framework
JAXP
Java API for XML Processing

 


Servlet Basics

Java Servlet API contains packages "javax.servlet" and "javax.servlet.http". Install JSDK.

servletrunner [options]

Minimal program (compile, run servletrunner, type URL http://the_host:8088/servlet/HelloWorldServlet):

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

public class HelloWorldServlet extends HttpServlet {
  public void doGet(HttpServletRequest req,  // request sent by browser
                    HttpServletResponse res) // response back to the browser
  throws ServletException, IOException {
    res.setContentType( "text/html" );
     // Output stream sent directly to the browser
    ServletOutputStream out = res.getOutputStream();
    // println statements to create an HTML page.
    out.println( "<html>" );
    out.println( "<head><title>Hello World</title></head>" );
    out.println( "<body>" <h1>Hello World</h1>" </body>" );
    out.println( "</html>" );
    out.close();
  }
}  

Run above program with

javac HelloWorldServlet.java
%ORACLE_HOME%\Apache\Jsdk\bin\servletrunner.exe -p 8080 -d E:\javadev

Or run on Apache with:

<html>
<header><title>call HelloWorldServlet</title></header>
<body>
<a href="http://server02/servlet/HelloWorldServlet">Call HelloWorldApp</a>
</body>
</html>

 

Simple post (use with HTML form below)

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

public class ExamplePostServlet extends HttpServlet {
  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
                throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
  
    out.println("<title>Example</title><body>");
    out.println("<h2>Button Clicked</h2>");

    String DATA = request.getParameter("DATA");
    if(DATA != null){
      out.println(DATA);
    } else {
      out.println("No text entered.");
    }
  
    out.println("<P>Return to <A HREF="thePageShownBelow.html">form</A>");
    out.close();
  }
}
   

Use the doPost() method with the following page:

<HTML>
<HEAD> <TITLE>Example</TITLE> </HEAD>
<BODY >
Enter text and click Submit button.<BR>
<FORM METHOD="POST" ACTION="/servlet/ExamplePostServlet">
<INPUT TYPE="TEXT" NAME="DATA" SIZE=30>
<INPUT TYPE="SUBMIT" VALUE="Click Me">
<INPUT TYPE="RESET">
</FORM>
</BODY>
</HTML>

 

Interface javax.servlet.Servlet:

init()
Called once when servlet is loaded by server.
service()
Read request and build response. Two parameters: ServletRequest object and ServletResponse object.
destroy()
Close files and database connections
getServletConfig()
Get ServletConfig object
getServletInfo()
Return string

In service() method, get the input stream with the getInputStream() method (pairs of names and values). Prepare response with method setContentType(). Send response with method getOutputStream() or getWriter() (return ServletOutputStream or PrintWriter)

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

public class AServlet implements Servlet {
  private ServletConfig theConfig;
  private aValue String;

  public void init (ServletConfig pConfig) throws ServletException {
    this.theConfig = pConfig;
    this.aValue = pConfig.getInitParameter("..."); // Get initalization parameters
    // Enumeration getInitParameterNames() --> parameter names
  }

  public void destroy() {}

  public ServletConfig getServletConfig() {
    return theConfig;
  }

  public String getServletInfo() {
    return "A Servlet";
  }

  public void service (HttpServletRequest req,  // request sent by browser
                       HttpServletResponse res) // response back to the browser
  throws ServletException, IOException {
    res.setContentType( "text/html" );
    PrintWriter out = res.getWriter();
    // See above
    out.println( "<html>...</html>" );
    out.close();
  }
}
   

 

 


Java Naming and Directory Interface 

Binding
Association between a name and an object.
Context
Set of (name-object) bindings, with a naming convention. A context provides a lookup.
Naming system
Contexts of the same type. A naming system provides a naming service.
Naming Service
Service provided by naming system
Directory Service
Naming Service with possibility of having attributes
Namespace
Set of names in a naming system
Composite Name
Name spaning several naming systems
Compound name
Name made of several atomic names

The JNDI architecture consists of an API which links an application with the Naming Manager. Then a service provider interface (SPI) makes the klink with a variety of naming and directory services. It is possible to download service providers.

javax.naming

javax.naming.directory

javax.naming.event

javax.naming.ldap

javax.naming.spi

See tutorial. See class doc

OC4J (see also below in Oracel Portal Specifics): JNDI initial context created for each application at startup of OC4J. The application's configuration XML files are used. The applications are defined in the server.xml configuration file. Typical code:
Context ctx = new InitialContext();
myEJBHome myhome = (HelloHome) ctx.lookup("java:comp/env/ejb/myEJB");

Note that in OC4J the default application is the global application.

 

 

 


JAAS - Java Authentication and Authorization 

 Two types: LDAP-Based Provider Type and XML-Based Provider Type (jazn-data.xml).

Java2 Security Model:

A java class is associated with a protection domain, which is linked to a set of permissions.

 JAAS privider in 9iAS:

 

 


JMS - Java Messaging Service

 Two models: Point-to-Point / queue (one consumer) or Publish and Subscribe / topics (broadcast to all registered listeners). Linked to JNDI.

Third-party message providers <--> JMS through ResourceProvider interface.

 


Oracle Portal Specifics (and Apache) 

Default location for servlets: .../Apache/Jserv/servlets
Compile with "%ORACLE_HOME%\apache\jsdk" in the classpath.

Servlets are managed by the OC4J servlet container; EJBs are managed by the OC4J EJB container. These containers, together with the JavaServer Pages container, form the core of OC4J.

OC4J: Configure a web.xml and archive these in a WAR file. Deploy the WAR file using the Deploy WAR File button on the OC4J Home Page. In the wizard, provide the URL servlet context as /j2ee/hello. Thus, the WAR is deployed into the /j2ee/hello servlet context. Make sure that OC4J is up and running.

Invoke with URL (port 7777 by default):
http://<apache_host>:<port>/j2ee/hello/servlet/HelloWorldServlet
If a context (see below) is defined in the application web.xml, then invoke with:
http://<apache_host>:<port>/j2ee/hello/world
Context:
<servlet-mapping>
  <servlet-name>[a.package.]HelloWorldServlet</servlet-name>
  <url-pattern>/world</url-pattern>
</servlet-mapping>

Minimal example

HTML form:
<html>
<head> <title>SQL with Servlet</title> </head>

<body>
<form method=GET action="/servlet/GetEmpInfo">
The query is<br>
SELECT LAST_NAME, EMPLOYEE_ID FROM EMPLOYEES WHERE LAST NAME LIKE ?.<p>

Enter the WHERE clause ? parameter (use % for wildcards).<br>
Example: 'S%':<br>
<input type=text name="queryVal">
<p>
<input type=submit>
</form>

</body>
</html>
Servlet:
import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.*;
import javax.sql.*;
import oracle.jdbc.*;

public class GetEmpInfo extends HttpServlet {

   DataSource ds = null;
   Connection conn = null;

   public void init() throws ServletException {
     try {
       InitialContext ic = new InitialContext();
       ds = (DataSource) ic.lookup("jdbc/OracleDS"); // see Data Sources below
       conn = ds.getConnection(); // or use getConnection(String username, String password);
     } catch (SQLException se) {
       throw new ServletException(se);
     } catch (NamingException ne) {
       throw new ServletException(ne);
     }
   }

   public void doGet (HttpServletRequest req, HttpServletResponse resp)
       throws ServletException, IOException {

     String queryVal = req.getParameter("queryVal");
     String query = "select last_name, employee_id from employees where last_name like " + queryVal;

     resp.setContentType("text/html");
     PrintWriter out = resp.getWriter();
     out.println("<html>");
     out.println("<head><title>GetEmpInfo</title></head>");
     out.println("<body>");

     try {
       Statement stmt = conn.createStatement();
       ResultSet rs = stmt.executeQuery(query);

       for (int count = 0; ; count++ ) {
         if (rs.next()) {
           out.println(rs.getString(1) + "   " + rs.getInt(2) + "<br>");
         } else {
           out.println("<h3>" + count + " rows retrieved</h3>");
           break;
         }
       }
       rs.close();
       stmt.close();
    }
     catch (SQLException se) {
       se.printStackTrace(out);
     }

     out.println("</body></html>");
   }

   public void destroy() {
     try {
       conn.close();
     }
     catch (SWLException ignored) {
     }
   }

}

 

 

 


Data Sources

A data source is an object that implements the javax.sql.DataSource interface. Three types:

OC4J data sources in data-sources.xml, as defined in in $J2EE_HOME/config/application.xml:
<data-sources
   path = "data-sources.xml"
/>
<data-sources path = "data-sources.xml" />

Data source definition:
<data-source
   class="com.evermind.sql.OrionCMTDataSource" // class that emulates the data source
   name="OracleDS" // optional
   location="jdbc/OracleCMTDS1" // this is the JNDI name
   connection-driver="oracle.jdbc.driver.OracleDriver"
   username="scott" // optional
   password="tiger" // optional
   url="jdbc:oracle:thin:@<hostname>:<TTC port number>:<DB SID>"
   inactivity-timeout="30" // seconds
/>

Re-start the OC4J server when data-sources.xml is changed.<data-source class="com.evermind.sql.OrionCMTDataSource" name="OracleDS" location="jdbc/OracleCMTDS1" connection-driver="oracle.jdbc.driver.OracleDriver" username="scott" password="tiger" url="jdbc:oracle:thin:@<hostname>:<TTC port number>:<DB SID>" inactivity-timeout="30" /> Mappings for JNDI names and data sources also defined in the files web.xml, ejb-jar.xml, orion-ejb-jar.xml, and the orion-web.xml.

Tag in the application web.xml or ejb-jar.xml files (Portable java:comp/env mechanism):
<resource-ref>
   <res-ref-name>jdbc/OracleDS</res-ref-name> // same name as in location of data-source
   <res-ref-name>jdbc/OracleMappedDS</res-ref-name> // must have mapping (see below)
   <res-type>javax.sql.DataSource</res-type>
   <res-auth>Container</res-auth>
</resource-ref>

Put is OC4J-specific XML file:
<resource-ref-mapping name="jdbc/OracleMappedDS" location="jdbc/OracleDS" /> // mapping if necessary

 

 

getConnection();
getConnection(String uid, String password);
Establish a database connection.
getLoginTimeout();
setLoginTimeout(int seconds);
Maximum timeout (seconds) for waiting for connection
 
getLogWriter();
setLogWriter(PrintWriter out);
Log writer for this data source. Returns a java.io.Printwriter object.
 

Part of sample code (compare with above):

Context ic = new InitialContext();
DataSource ds = (DataSource) ic.lookup("jdbc/OracleDS"); // as defined in data-source
DataSource ds = (DataSource) ic.lookup("java:comp/env/jdbc/OracleMappedDS"); // JNDI reference (portable)
oracle.jdbc.OracleConnection conn = (oracle.jdbc.OracleConnection) ds.getConnection(userName, passWord);

      // or use without parameters, username/pw in data source definition
      // The casting is necessary for JDBC oracle.jdbc.* objects
oracle.jdbc.Statement orclStmt = (oracle.jdbc.OracleStatement)conn.createStatement();
oracle.jdbc.OracleResultSet rs = orclStmt.executeQuery("SELECT * FROM ...");
while (rs.next()) {
   oracle.sql.ARRAY array = rs.getARRAY(1);
 ...
}

Use SQLJ or JDBC to execute queries.

Connections with transaction and those without via the same data source are pooled.

 


J2EE

 

Deployment

Enterprise Application .ear META-INF/application.xml
Enterprise JavaBean Module (EJB) .jar META-INF/ejb-jar.xml
Web Application .war WEB-INF/web.xml
Web Service (similar to Web Appl) .ear or .war WEB_INF/web-services.xml
Connector Module (Resource Adapters) .rar META-INF/ra.xml
Startup or Shutdown Class n/a No deployment descriptor (Class file only)

 

Staging
Copies the archive files (.jar...) into a new location so as to make the application available to a server.
 

 

 

 

 


.JSP Pages

Continue here . One tutorial done on visualBuilder.com.

Exercises at http://localhost:8080/exercises.jsp

 

The JSP specification is defined on top of the Servlet API. It allows separation of the presentation from the content. Changes to the presentation do not need recompilation as with servlets.

 

JSP action

 

Directives

<%@ ... %> The two main directives are page and include. See page directives in table below.

Declaration: <%! int i = 0; %> (end in semicolon). Note that variables declared here have a scope beyond the current page.
Expressions: <%= ... %> (no semicolon)
Scriptlets: <%  ... %>
Comments: <%-- comment not sent to client --%>    <!-- comment visible on client --%>

Implicit Object Type of object Scope  
request Javax.servlet.http.HttpServletRequest Request Trigger of the service invocation
response Javax.servlet.http.HttpServletResponse Page  
pageContext Javax.servlet.jsp.PageContext Page  
application Javax.servlet.http.ServletContext Application Obtained from servlet configuration object
out Javax.servlet.jsp.JspWriter Page Writes into the output stream
config Javax.servlet.http.ServletConfig Page Stores the servlet's configuration data.
Use <% String devStr = request.getParameter("dev"); %>
page Java.lang.Object (HttpJspPage) Page Synonym for the "this" operator. Not used often by page authors. Represents the jsp page
session Javax.servlet.http.HttpSession    
exception Throwable Page Uncaught Throwable object linked to error

 

Page directives

Page Directive Comment Sample Code
language Language of the page <%@ page language = "java" %>
extends Superclass. <%@ page extends = "com.taglibrary... %>
import Import classes in a java package into the current JSP page. <%@ page import = "java.util.*" %>
session By default session data is available. Switching to false has performance benefits <%@ page session = "false" %>
buffer For buffered output; default is 8 Kb <%@ page buffer = "none" %>
autoFlush Flush the output buffer when it is full. <%@ page autoFlush = "true" %>
isThreadSafe Allows the possibility of multiple requests?  
info Add information or document for a page, for example author, version, copyright and date info <%@ page info = "Material from www.visualbuilder.com" %>
errorPage Define an error page; the current page is therefore not an error page <%@ page isErrorPage="false" errorPage="errorHandler.jsp" %>
IsErrorPage Set to true for JSP error page. Gives access to the implicit object exception. <%@ page isErrorPage="true" %>
contentType Set the mime type and character set of the JSP. <%@ page contentType="..." %>

Example:

Sample code
<%!
  public String writeThis(int x)
  {
     String myText="";
     for (int i = 1; i < x; i++ )
      myText = myText + "<font size=" + i + " color=darkred face=verdana>VisualBuilder JSP Tutorial</font><br>" ;
    return myText;
  }
%>
This is a loop example from the
<%= writeThis(8) %>

 

<%
   String name = request.getParameter( "username" );
   session.setAttribute( "theName", name );
%>

Hello, <%= session.getAttribute( "theName" ) %>

 

Form:

<form action="myformresponse.jsp" method="post">
<input type="text" name="the_textbox"><br>
<input type="submit" name="submit">
</form>

In the myformresponse.jsp, put:
<% String sName = request.getParameter("the_textbox");
out.print(sName); %>

Other information:
<% String sHostIPAddress=request.getRemoteAddr()%>
<% String sHostName=request.getRemoteHost()%>

The full URL as shown in the address bar is made up of:
request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath()

 

Try this example:

<HTML>
<HEAD>
<!-- Example2 -->
<TITLE> JSP loop</TITLE>
</HEAD>
<BODY>
<font face=verdana color=darkblue>
JSP loop
<BR> <BR>
<%!
public String writeThis(int x)
{
String myText="";
for (int i = 1; i < x; i )
myText = myText "<font size=" i " color=darkred face=verdana>VisualBuilder JSP Tutorial</font><br>" ;
return myText;
}
%>


This is a loop example from the

<br>
<%= writeThis(8) %>
</font>
</BODY>
</HTML>

 

Syntax

if( session.getAttribute("the_name") != null) a_var = session.getAttribute("the_name"); else {}; String a_var = request.getParameter("param") == null ? "" : request.getParameter("param");

 

Error handling:

do this: http://java.sun.com/developer/onlineTraining/JSPIntro/exercises/ErrorHandling/index.html

 

 

Continue reading this page, in particular, the exercises: http://java.sun.com/developer/onlineTraining/JSPIntro/contents.html

Tag tutorial: http://java.sun.com/products/jsp/tutorial/TagLibrariesTOC.html

 

 

 

 


Basic Web Application

 

Web Application File Structure

The source files are copied into the web-inf structure.
The web.xml file indicates where the default page is, here index.jsp. It is also called a deployment descriptor.
The WebRoot is structured after the J2EE Web Archive Structure
The WEB-INF contains non-public resources. The child directory classes contains the result of compiliations of what is in src. The child directory lib (not shown here) contain the jar files
mymetadata and the myeclipse folder are important for Eclipse.

.project
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
    <name>SimpleJSPExample</name>
    <comment></comment>
    <projects>
    </projects>
    <buildSpec>
        <buildCommand>
            <name>com.genuitec.eclipse.j2eedt.core.WebClasspathBuilder</name>
            <arguments>
            </arguments>
        </buildCommand>
        <buildCommand>
            <name>org.eclipse.jdt.core.javabuilder</name>
            <arguments>
            </arguments>
        </buildCommand>
        <buildCommand>
            <name>com.genuitec.eclipse.j2eedt.core.J2EEProjectValidator</name>
            <arguments>
            </arguments>
        </buildCommand>
        <buildCommand>
            <name>com.genuitec.eclipse.j2eedt.core.DeploymentDescriptorValidator</name>
            <arguments>
            </arguments>
        </buildCommand>
        <buildCommand>
            <name>org.eclipse.wst.validation.validationbuilder</name>
            <arguments>
            </arguments>
        </buildCommand>
        <buildCommand>
            <name>com.genuitec.eclipse.ast.deploy.core.DeploymentBuilder</name>
            <arguments>
            </arguments>
        </buildCommand>
    </buildSpec>
    <natures>
        <nature>com.genuitec.eclipse.ast.deploy.core.deploymentnature</nature>
        <nature>com.genuitec.eclipse.j2eedt.core.webnature</nature>
        <nature>org.eclipse.jdt.core.javanature</nature>
    </natures>
</projectDescription>

 

.mymetadata
<?xml version="1.0" encoding="UTF-8"?>
<project-module
    type="WEB"
    name="SimpleJSPExample"
    id="myeclipse.1187813132046"
    context-root="/SimpleJSPExample"
    j2ee-spec="1.4"
    archive="SimpleJSPExample.war">
    <attributes>
        <attribute name="webrootdir" value="WebRoot" />
    </attributes>
</project-module>

 

.classpath
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry kind="src" path="src"/>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
    <classpathentry kind="con" path="com.genuitec.eclipse.j2eedt.core.J2EE14_CONTAINER"/>
    <classpathentry kind="output" path="WebRoot/WEB-INF/classes"/>
</classpath>

 

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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">
// The following have to be confirmed for version 2.4
<display-name>
    The name of the application
</display-name>
<description>
    
</description>

<context-param>
    <param-name>name</param-name>
    <param-value>value</param-value>
    <description>...</description>
    </context-param>

<servlet>
    <servlet-name>name</servlet-name>
    <description>...</description>
    <servlet-class>com.appllic.path.servlet_name</servlet-class>
    <init-param>
        <param-name>name</param-name>
        <param-value>value</param-value>
    </init-param>
</servlet>

<servlet-mapping>
    <servlet-name>name</servlet-name>
    <url-pattern>*.a_pattern</url-pattern>
</servlet-mapping>

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<servlet-mapping>
    <servlet-name>image_name</servlet-name>
    <url-pattern>/image_path</url-pattern>
</servlet-mapping>

<session-config>
    <session-timeout>30</session-timeout>
</session-config>
</web-app>

Get the context parameters with: String value = getServletContext().getInitParameter("name from context-param element"); 
Get the servlet parameters with: String value = getServletConfig().getInitParameter("name from init-param tag inside servlet tag");

 

 

 


Eclipse

 

Continue reading http://www.myeclipseide.com/documentation/quickstarts/webprojects/

Change the perspective: menu window > open perspective > choose (in "other", click in box to see all). The perspective name shows in the title bar.
Generally Enterprise Workbench for J2EE development, Java for simple java programs.

View the package explorer: Window > Show View > Java > Package Explorer.
See any view: Window > Show View > Other...

Reset the perspective: Window > Reset Perspective

Add a new file in windows, then just right-click the folder in the navigator and refresh to see the file.

Add a new web project: first copy the files to the workspace, then menu > new > web project. This operation, however, overwrites the web.xml so you should download the web.xml again.
To create a new web project from scratch: File > New > Project > MyEclipse > J2EE Projects > Web Project. Enter the project name. The other fields are usually prepopulated from the template
The context root URL is the part that comes after the server name in the address bar after the project is deployed. It is the project name by default. Generally add the JSTL libraries.

Watch the folding in the left margin: some code may not be visible

Run a web application: right-click on the project > Debug As... > MyEclipse Server Application. This starts the embedded Tomcat server

Add a new jsp page: New > Other > MyEclipse > Web > JSP. Page generally goes in /context/WebRoot

Some validation occurs in the editor. To further validate, do menu project > clean. Enable automatic validation with menu project > Build Automatically. Also see the project properties (right-click on project) > properties > MyEclipse > validation

Deploy: click on the "add" button and choose the target application server. The applicaiton is available at http://localhost:8080/the_context_root. Undeploy by choosing the "remove" button.

Transform an existing project to be an Eclipse web project: MyEclipse > Add Web Capabilities...

Search in current file: ^F.
Search in the workspace: ^H; next occurrent: see the down arrow in the toolbar of the search results screen.

 

 


Problems and Solutions