Java Servlets and J2EEThese are my personal notes that I use as a quick help in my work.
|
|
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:
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.*; |
Run above program with
javac HelloWorldServlet.java |
Or run on Apache with:
<html> |
Simple post (use with HTML form below)
import java.io.*; public class ExamplePostServlet extends HttpServlet { |
Use the doPost() method with the following page:
<HTML> |
Interface javax.servlet.Servlet:
init()
service()
destroy()
getServletConfig()
getServletInfo()
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.*; |
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.
Context
interface, which includes lookup()
.Binding
objects contain name, class and object; use listBindings()
to return an enumeration of Bindings;
use list()
to get an enumeration of NameClassPair
objects.Reference
class is used for storing information on how to access
an objectInitialContext
is the starting point for looking up informationNamingExceptions
classDirContext
interface represents a directory context; it is
an extension of the Context interface.getAttribute(), modifyAttribute()
search()
method 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.
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.
java.security.Principal
,
linked to a namespace.javax.security.auth.Subject
class) corresponds to
one entity, but with multiple identities (principles).LoginContext
class, specifically with LoginContext.login()
. Get the subject
with LoginContext.getSubject()
. JAAS privider in 9iAS:
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.
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.*; |
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
<data-sources path = "data-sources.xml" />
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);
getLoginTimeout();
setLoginTimeout(int seconds);
getLogWriter();
setLogWriter(PrintWriter out);
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.
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) |
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
<jsp:getProperty name="bean" property="property" />
<jsp:usebean id = " ...." scope = "page | request | session | application"
class = "com..." />
with scope equal to page (until page completes), request (linked to the client
request), session (client session) or application
Directives
<%@ ... %>
The two main directives are page and include. See
page directives in table below.<%@ include file="relative URL" %>
<%@ include file="nav_menu.jsp" %>
<%@ page ... %>
<%@ taglib uri="tag library URI" prefix = "tagPrefix" %>
<tagPrefix:tagName attribute="the value">...</tagPrefix:tagName>
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 |
---|
<%! |
<%
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>
|
if( session.getAttribute("the_name") != null) a_var = session.getAttribute("the_name"); else {};
String a_var = request.getParameter("param") == null ? "" : request.getParameter("param");
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
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"?> |
.mymetadata |
---|
<?xml version="1.0" encoding="UTF-8"?> |
.classpath |
---|
<?xml version="1.0" encoding="UTF-8"?> |
web.xml |
---|
<?xml version="1.0" encoding="UTF-8"?> |
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");
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.