The Java Database Connectivity (JDBC) API is used to access a SQL database from a Java application. JDBC also supports tabular data sources, such as a spreadsheet.
Oracle JDeveloper is a free Integrated Development Environment (IDE) for modeling, developing, debugging, optimizing, and deploying Java applications. JDeveloper 10g is used to develop J2EE applications comprising the JSPs, EJBs, struts, servlets, and Java classes that may require accessing a database table in an Oracle 10g Database or a third-party database. In this extract from the book JDBC 4.0 and Oracle JDeveloper for J2EE Development (Packt Publishing), we will see how to configure JDBC in the JDeveloper IDE.
Unlike the Eclipse IDE, which requires a plug-in, JDeveloper has a built-in provision to establish a JDBC connection with a database. JDeveloper is the only Java IDE with an embedded application server, Oracle Containers for J2EE (OC4J) or WebLogic Server in JDeveloper 11g. Thus a database-based Web application may run in JDeveloper without a third-party application server. However, JDeveloper also supports third-party application servers. Starting with JDeveloper 11, application developers can point the IDE to an application server instance, including third-party application servers, that you want to use for testing during development. JDeveloper provides connection pooling for the efficient use of database connections. A database connection may be used in an ADF BC (Business Components) application or in a Java EE application.
A database connection in JDeveloper may be configured in the Connections Navigator. A Connections Navigator connection is available as a DataSource registered with a JNDI naming service. The database connection in JDeveloper is a reusable named connection that developers configure once and then use in as many of their projects as they want. Depending on the nature of the project and the database connection, the connection is configured in the bc4j.xcfg file or a Java EE data source. Here, it is necessary to distinguish between data source and DataSource. A data source is a source of data; for example, an RDBMS database is a data source. A DataSource is an interface that represents a factory for JDBC Connection objects.
JDeveloper uses the term Data Source or data source to refer to a factory for connections. We will also use the term Data Source or data source to refer to a factory for connections, which in the javax.sql package is represented by the DataSource interface. A DataSource object may be created from a data source registered with the JNDI (Java Naming and Directory) naming service using JNDI lookup. A JDBC Connection object may be obtained from a DataSource object using the getConnection method. As an alternative to configuring a connection in the Connections Navigator, a data source may also be specified directly in the data source configuration file data-sources.xml.
In this article we will discuss the procedure to configure a JDBC connection and a JDBC data source in JDeveloper 10g IDE. We will use the MySQL 5.0 database server and MySQL Connector/J 5.1 JDBC driver, which support the JDBC 4.0 specification. In this article you will learn the following:
* Creating a database connection in JDeveloper Connections Navigator.
* Configuring the Data Source and Connection Pool associated with the connection configured in the Connections Navigator.
* The common JDBC Connection Errors.
Before we create a JDBC connection and a data source we will discuss connection pooling and DataSource.
Connection Pooling and DataSource
The javax.sql package provides the API for server-side database access. The main interfaces in the javax.sql package are DataSource, ConnectionPoolDataSource, and PooledConnection. The DataSource interface represents a factory for connections to a database. DataSource is a preferred method of obtaining a JDBC connection. An object that implements the DataSource interface is typically registered with a Java Naming and Directory API-based naming service. DataSource interface implementation is driver-vendor specific. The DataSource interface has three types of implementations:
* Basic implementation: In a basic implementation there is a 1:1 correspondence between a client`s Connection object and the connection with the database. This implies that for every Connection object, there is a connection with the database. With the basic implementation, the overhead of opening, initiating, and closing a connection is incurred for each client session.
* Connection pooling implementation: A pool of Connection objects is available from which connections are assigned to the different client sessions. A connection pooling manager implements the connection pooling. When a client session does not require a connection, the connection is returned to the connection pool and becomes available to other clients. Thus, the overheads of opening, initiating, and closing connections are reduced.
* Distributed transaction implementation: Distributed transaction implementation produces a Connection object that is mostly used for distributed transactions and is always connection-pooled. A transaction manager implements the distributed transactions.
An advantage to using a data source is that code accessing a data source does not have to be modified when an application is migrated to a different application server. Only the data source properties need to be modified. A JDBC driver that is accessed with a DataSource does not register itself with a DriverManager. A DataSource object is created using a JNDI lookup and subsequently a Connection object is created from the DataSource object. For example, if a data source JNDI name is jdbc/OracleDS, a DataSource object may be created using JNDI lookup. First, create an InitialContext object and subsequently create a DataSource object using the InitialContext lookup method. From the DataSource object create a Connection object using the getConnection() method:
InitialContext ctx=new InitialContext();
DataSource ds=ctx.lookup("jdbc/OracleDS");
Connection conn=ds.getConnection();
The JNDI naming service, which we used to create a DataSource object, is provided by J2EE application servers such as the Oracle Application Server Containers for J2EE (OC4J) embedded in the JDeveloper IDE.
A connection in a pool of connections is represented by the PooledConnection interface, not the Connection interface. The connection pool manager, typically the application server, maintains a pool of PooledConnection objects. When an application requests a connection using the DataSource.getConnection() method, as we did using the jdbc/OracleDS data source example, the connection pool manager returns a Connection object, which is actually a handle to an object that implements the PooledConnection interface.
A ConnectionPoolDataSource object, which is typically registered with a JNDI naming service, represents a collection of PooledConnection objects. The JDBC driver provides an implementation of the ConnectionPoolDataSource, which is used by the application server to build and manage a connection pool. When an application requests a connection, if a suitable PooledConnection object is available in the connection pool, the connection pool manager returns a handle to the PooledConnection object as a Connection object. If a suitable PooledConnection object is not available, the connection pool manager invokes the getPooledConnection() method of the ConnectionPoolDataSource to create a new PooledConnection object. For example, if connectionPoolDataSource is a ConnectionPoolDataSource object, a new PooledConnection gets created as follows:
PooledConnection
pooledConnection=connectionPoolDataSource.getPooledConnection();
The application does not have to invoke the getPooledConnection() method though; the connection pool manager invokes the getPooledConnection() method and the JDBC driver implementing the ConnectionPoolDataSource creates a new PooledConnection and returns a handle to it. The connection pool manager returns a Connection object, which is a handle to a PooledConnection object, to the application requesting a connection. When an application closes a Connection object using the close() method, as follows, the connection does not actually get closed.
conn.close();
The connection handle gets deactivated when an application closes a Connection object with the close() method. The connection pool manager does the deactivation. When an application closes a Connection object with the close() method, any client info properties that were set using the setClientInfo method are cleared.
The connection pool manager is registered with a PooledConnection object using the addConnectionEventListener() method. When a connection is closed, the connection pool manager is notified and the connection pool manager deactivates the handle to the PooledConnection object and returns the PooledConnection object to the connection pool to be used by another application.
The connection pool manager is also notified if a connection has an error. A PooledConnection object is not closed until the connection pool is being reinitialized, the server is shutdown, or a connection becomes unusable.
In addition to connections being pooled, PreparedStatement objects are also pooled by default if the database supports statement pooling. It can be discovered if a database supports statement pooling using the supportsStatementPooling() method of the DatabaseMetaData interface. The PreparedStatement pooling is also managed by the connection pool manager. To be notified of PreparedStatement events such as a PreparedStatement getting closed or a PreparedStatement becoming unusable, a connection pool manager is registered with a PooledConnection manager using the addStatementEventListener() method. A connection pool manager deregisters a PooledConnection object using the removeStatementEventListener() method. Methods addStatementEventListener and removeStatementEventListener are new methods in the PooledConnection interface in JDBC 4.0. Pooling of Statement objects is another new feature in JDBC 4.0. The Statement interface has two new methods in JDBC 4.0 for Statement pooling: isPoolable() and setPoolable().
The isPoolable method checks if a Statement object is poolable and the setPoolable method sets the Statement object to poolable. When an application closes a PreparedStatement object using the close() method, the PreparedStatement object is not actually closed. The PreparedStatement object is returned to the pool of PreparedStatements. When the connection pool manager closes a PooledConnection object by invoking the close() method of PooledConnection, all the associated statements also get closed. Pooling of PreparedStatements provides significant optimization, but if a large number of statements are left open, it may not be an optimal use of resources. Thus, the following procedure is followed to obtain a connection in an application server using a data source:
1. Create a data source with a JNDI name binding to the JNDI naming service.
2. Create an InitialContext object and look up the JNDI name of the data source using the lookup method to create a DataSource object. If the JDBC driver implements the DataSource as a connection pool, a connection pool becomes available.
3. Request a connection from the connection pool. The connection pool manager checks if a suitable PooledConnection object is available. If a suitable PooledConnection object is available, the connection pool manager returns a handle to the PooledConnection object as a Connection object to the application requesting a connection.
4. If a PooledConnection object is not available, the connection pool manager invokes the getPooledConnection() method of the ConnectionPoolDataSource, which is implemented by the JDBC driver.
5. The JDBC driver implementing the ConnectionPoolDataSource creates a PooledConnection object and returns a handle to it.
6. The connection pool manager returns a handle to the PooledConnection object as a Connection object to the application requesting a connection.
7. When an application closes a connection, the connection pool manager deactivates the handle to the PooledConnection object and returns the PooledConnection object to the connection pool.
ConnectionPoolDataSource provides some configuration properties to configure a connection pool. The configuration pool properties are not set by the JDBC client, but are implemented or augmented by the connection pool. The properties can be set in a data source configuration. Therefore, it is not for the application itself to change the settings, but for the administrator of the pool, who also sometimes happens to be the developer, to do so.
Friday, November 6, 2009
Monday, August 24, 2009
Struts 2 Hello World Example
I had seen many new deveopers struggling against struts2 hello world example. So I decided to write a small example.
Below are the required libraries to run this example which are easily availabel
struts2-core-2.0.11
xwork-2.0.4
commons-logging-1.0.4
commons-logging-api-1.1
freemarker-2.3.8
ognl-2.6.11
The structure of the applictaion which I am following is (Eclipse IDE)
Struts2Demo
|---src
| |----org
| | |----vinod
| | | |----action
| | | | |----HelloWorld।java
|---struts.xml
|---WebContent
| |---jsp
| |---HelloWorld।jsp
|---index.jsp
|---WEB-INF
| |---lib
| |---web.xml
It is true that different IDE's use different structure, but at last when war is build they follow same structure.
Lets start...
HelloWorld.java
package org.vinod.action;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorld extends ActionSupport{
String greetings = null;
public String execute() throws Exception {
setGreetings("Hello World");
return SUCCESS;
}
/**
* @return the greetings
*/
public String getGreetings() {
return greetings;
}
/**
* @param greetings the greetings to set
*/
public void setGreetings(String greetings) {
this.greetings = greetings;
}
}
HelloWorld.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
Struts 2 Example
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
Struts 2 Example
struts.xml
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
class="org.vinod.action.HelloWorld">
/jsp/HelloWorld.jsp
web.xml
struts2
org.apache.struts2.dispatcher.FilterDispatcher
struts2
/*
index.jsp
Below are the required libraries to run this example which are easily availabel
struts2-core-2.0.11
xwork-2.0.4
commons-logging-1.0.4
commons-logging-api-1.1
freemarker-2.3.8
ognl-2.6.11
The structure of the applictaion which I am following is (Eclipse IDE)
Struts2Demo
|---src
| |----org
| | |----vinod
| | | |----action
| | | | |----HelloWorld।java
|---struts.xml
|---WebContent
| |---jsp
| |---HelloWorld।jsp
|---index.jsp
|---WEB-INF
| |---lib
| |---web.xml
It is true that different IDE's use different structure, but at last when war is build they follow same structure.
Lets start...
HelloWorld.java
package org.vinod.action;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorld extends ActionSupport{
String greetings = null;
public String execute() throws Exception {
setGreetings("Hello World");
return SUCCESS;
}
/**
* @return the greetings
*/
public String getGreetings() {
return greetings;
}
/**
* @param greetings the greetings to set
*/
public void setGreetings(String greetings) {
this.greetings = greetings;
}
}
HelloWorld.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
struts.xml
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
web.xml
Friday, August 14, 2009
Spring Properties File Based Data Injection
File: helloworld-context.properties
source.(class)=SimpleMessageData
destination.(class)=StdoutMessageReporter
service.(class)=DefaultMessageService
service.source(ref)=source
service.destination(ref)=destination
File: Main.java
import org.springframework.beans.factory.support.BeanDefinitionReader;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
public class Main {
public static void main(String[] a) {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
BeanDefinitionReader reader = new PropertiesBeanDefinitionReader(bf);
reader.loadBeanDefinitions(new ClassPathResource("helloworld-context.properties"));
MessageService service = (MessageService) bf.getBean("service");
service.execute();
}
}
interface MessageService {
void execute();
}
class DefaultMessageService implements MessageService {
private MessageData source;
private MessageReporter destination;
public void execute() {
this.destination.write(this.source.getMessage());
}
public void setSource(MessageData source) {
this.source = source;
}
public void setDestination(MessageReporter destination) {
this.destination = destination;
}
}
interface MessageReporter {
void write(String message);
}
interface MessageData {
String getMessage();
}
class StdoutMessageReporter implements MessageReporter {
public void write(String message) {
System.out.println(message);
}
}
class SimpleMessageData implements MessageData {
private final String message;
public SimpleMessageData() {
this("Hello, world");
}
public SimpleMessageData(String message) {
this.message = message;
}
public String getMessage() {
return this.message;
}
}
click here
source.(class)=SimpleMessageData
destination.(class)=StdoutMessageReporter
service.(class)=DefaultMessageService
service.source(ref)=source
service.destination(ref)=destination
File: Main.java
import org.springframework.beans.factory.support.BeanDefinitionReader;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
public class Main {
public static void main(String[] a) {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
BeanDefinitionReader reader = new PropertiesBeanDefinitionReader(bf);
reader.loadBeanDefinitions(new ClassPathResource("helloworld-context.properties"));
MessageService service = (MessageService) bf.getBean("service");
service.execute();
}
}
interface MessageService {
void execute();
}
class DefaultMessageService implements MessageService {
private MessageData source;
private MessageReporter destination;
public void execute() {
this.destination.write(this.source.getMessage());
}
public void setSource(MessageData source) {
this.source = source;
}
public void setDestination(MessageReporter destination) {
this.destination = destination;
}
}
interface MessageReporter {
void write(String message);
}
interface MessageData {
String getMessage();
}
class StdoutMessageReporter implements MessageReporter {
public void write(String message) {
System.out.println(message);
}
}
class SimpleMessageData implements MessageData {
private final String message;
public SimpleMessageData() {
this("Hello, world");
}
public SimpleMessageData(String message) {
this.message = message;
}
public String getMessage() {
return this.message;
}
}
click here
Saturday, August 8, 2009
Stereotype Annotations Cut Down XML Configuration in Spring
getname.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
"http://www.w3.org/TR/html4/loose.dtd">
Greeting Request
---------------------------------------------------
HelloWorldController.java
package com.intertech.mvc;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class HelloWorldController {
@ModelAttribute("name")
public String populateName(
@RequestParam(value = "name", required = false) String name) {
return name;
}
@RequestMapping(value = "/greeting.request", method = RequestMethod.POST)
protected String sayHello() {
return "greet";
}
@RequestMapping(value = "/greeting.request", method = RequestMethod.GET)
protected String showForm() {
return "getname";
}
}
---------------------------------------------------
web.xml
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
HelloWorldAnnotated
dispatcher
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
/WEB-INF/mvc-beans.xml
dispatcher
*.request
*.xls
index.html
---------------------------------------------------
mvc-beans.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
---------------------------------------------------
greet.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
"http://www.w3.org/TR/html4/loose.dtd">
Greeting
---------------------------------------------------
Note :
Add the commons-logging.jar, spring.jar and spring-webmvc.jar (Spring 2.5 or better) to the
/WEB-INF/lib folder.
To run HelloWorld, deploy the application to a Web Container, then request getname.jsp with the
following URL:
http://localhost:8080/HelloWorldAnnotated/getname.jsp
Because the controller has RequestMapping for both POST and GET HTTP methods, you can also
run HelloWorld by requesting the following URL:
http://localhost:8080/HelloWorldAnnotated/greeting.request
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
"http://www.w3.org/TR/html4/loose.dtd">
---------------------------------------------------
HelloWorldController.java
package com.intertech.mvc;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class HelloWorldController {
@ModelAttribute("name")
public String populateName(
@RequestParam(value = "name", required = false) String name) {
return name;
}
@RequestMapping(value = "/greeting.request", method = RequestMethod.POST)
protected String sayHello() {
return "greet";
}
@RequestMapping(value = "/greeting.request", method = RequestMethod.GET)
protected String showForm() {
return "getname";
}
}
---------------------------------------------------
web.xml
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
---------------------------------------------------
mvc-beans.xml
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
---------------------------------------------------
greet.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
"http://www.w3.org/TR/html4/loose.dtd">
Hello ${name}
---------------------------------------------------
Note :
Add the commons-logging.jar, spring.jar and spring-webmvc.jar (Spring 2.5 or better) to the
/WEB-INF/lib folder.
To run HelloWorld, deploy the application to a Web Container, then request getname.jsp with the
following URL:
http://localhost:8080/HelloWorldAnnotated/getname.jsp
Because the controller has RequestMapping for both POST and GET HTTP methods, you can also
run HelloWorld by requesting the following URL:
http://localhost:8080/HelloWorldAnnotated/greeting.request
In Eclipse, is there a way to run the Javadoc tool against my code?
The answer is yes! While I knew this was possible, I wasn’t exactly sure of how this is done. It turns out using Javadoc from within Eclipse is a piece of cake. Given your Eclipse IDE is already configured to use the tools from a JDK, chances are good that it is already setup to generate Javadocs for your code with a simple menu selection. In Eclipse, look for the Project menu option on the Eclipse menu bar. Select Generate Javadoc… from the Project pull-down menu.

This should cause the Generate Javadoc window to open where you can specify what members should be included (private up to public) and where the documents generated should be put. If the JDK’s bin folder and/or the javadoc.exe tool can’t be found, the same window allows you to point Eclipse to a valid Javadoc generating tool and configure it per your needs.

Once the Javadocs are created, the documents are used by Eclipse to produce hovers over the classes, methods, variables, etc.

This should cause the Generate Javadoc window to open where you can specify what members should be included (private up to public) and where the documents generated should be put. If the JDK’s bin folder and/or the javadoc.exe tool can’t be found, the same window allows you to point Eclipse to a valid Javadoc generating tool and configure it per your needs.

Once the Javadocs are created, the documents are used by Eclipse to produce hovers over the classes, methods, variables, etc.
Friday, August 7, 2009
Interface Servlet,JspPage,HttpJspPage
javax.servlet
Interface Servlet
All Known Implementing Classes:
GenericServlet, HttpServlet
public interface Servlet
Defines methods that all servlets must implement.
A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol.
To implement this interface, you can write a generic servlet that extends javax.servlet.GenericServlet or an HTTP servlet that extends javax.servlet.http.HttpServlet.
This interface defines methods to initialize a servlet, to service requests, and to remove a servlet from the server. These are known as life-cycle methods and are called in the following sequence:
1. The servlet is constructed, then initialized with the init method.
2. Any calls from clients to the service method are handled.
3. The servlet is taken out of service, then destroyed with the destroy method, then garbage collected and finalized.
In addition to the life-cycle methods, this interface provides the getServletConfig method, which the servlet can use to get any startup information, and the getServletInfo method, which allows the servlet to return basic information about itself, such as author, version, and copyright.
Method Summary
void destroy()
Called by the servlet container to indicate to a servlet that the servlet is being taken out of service.
ServletConfig getServletConfig()
Returns a ServletConfig object, which contains initialization and startup parameters for this servlet.
java.lang.String getServletInfo()
Returns information about the servlet, such as author, version, and copyright.
void init(ServletConfig config)
Called by the servlet container to indicate to a servlet that the servlet is being placed into service.
void service(ServletRequest req, ServletResponse res)
Called by the servlet container to allow the servlet to respond to a request.
Method Detail
init
public void init(ServletConfig config)
throws ServletException
Called by the servlet container to indicate to a servlet that the servlet is being placed into service.
The servlet container calls the init method exactly once after instantiating the servlet. The init method must complete successfully before the servlet can receive any requests.
The servlet container cannot place the servlet into service if the init method
1. Throws a ServletException
2. Does not return within a time period defined by the Web server
Parameters:
config - a ServletConfig object containing the servlet's configuration and initialization parameters
Throws:
ServletException - if an exception has occurred that interferes with the servlet's normal operation
See Also:
UnavailableException, getServletConfig()
getServletConfig
public ServletConfig getServletConfig()
Returns a ServletConfig object, which contains initialization and startup parameters for this servlet. The ServletConfig object returned is the one passed to the init method.
Implementations of this interface are responsible for storing the ServletConfig object so that this method can return it. The GenericServlet class, which implements this interface, already does this.
Returns:
the ServletConfig object that initializes this servlet
See Also:
init(javax.servlet.ServletConfig)
service
public void service(ServletRequest req,
ServletResponse res)
throws ServletException,
java.io.IOException
Called by the servlet container to allow the servlet to respond to a request.
This method is only called after the servlet's init() method has completed successfully.
The status code of the response always should be set for a servlet that throws or sends an error.
Servlets typically run inside multithreaded servlet containers that can handle multiple requests concurrently. Developers must be aware to synchronize access to any shared resources such as files, network connections, and as well as the servlet's class and instance variables. More information on multithreaded programming in Java is available in the Java tutorial on multi-threaded programming.
Parameters:
req - the ServletRequest object that contains the client's request
res - the ServletResponse object that contains the servlet's response
Throws:
ServletException - if an exception occurs that interferes with the servlet's normal operation
java.io.IOException - if an input or output exception occurs
getServletInfo
public java.lang.String getServletInfo()
Returns information about the servlet, such as author, version, and copyright.
The string that this method returns should be plain text and not markup of any kind (such as HTML, XML, etc.).
Returns:
a String containing servlet information
destroy
public void destroy()
Called by the servlet container to indicate to a servlet that the servlet is being taken out of service. This method is only called once all threads within the servlet's service method have exited or after a timeout period has passed. After the servlet container calls this method, it will not call the service method again on this servlet.
This method gives the servlet an opportunity to clean up any resources that are being held (for example, memory, file handles, threads) and make sure that any persistent state is synchronized with the servlet's current state in memory.
---------------------------------------------------------------
javax.servlet.jsp
Interface JspPage
All Superinterfaces:
Servlet
All Known Subinterfaces:
HttpJspPage
public interface JspPage
extends Servlet
The JspPage interface describes the generic interaction that a JSP Page Implementation class must satisfy; pages that use the HTTP protocol are described by the HttpJspPage interface.
Two plus One Methods
The interface defines a protocol with 3 methods; only two of them: jspInit() and jspDestroy() are part of this interface as the signature of the third method: _jspService() depends on the specific protocol used and cannot be expressed in a generic way in Java.
A class implementing this interface is responsible for invoking the above methods at the appropriate time based on the corresponding Servlet-based method invocations.
The jspInit() and jspDestroy() methods can be defined by a JSP author, but the _jspService() method is defined automatically by the JSP processor based on the contents of the JSP page.
_jspService()
The _jspService()method corresponds to the body of the JSP page. This method is defined automatically by the JSP container and should never be defined by the JSP page author.
If a superclass is specified using the extends attribute, that superclass may choose to perform some actions in its service() method before or after calling the _jspService() method. See using the extends attribute in the JSP_Engine chapter of the JSP specification.
The specific signature depends on the protocol supported by the JSP page.
public void _jspService(ServletRequestSubtype request,
ServletResponseSubtype response)
throws ServletException, IOException;
Method Summary
void jspDestroy()
The jspDestroy() method is invoked when the JSP page is about to be destroyed.
void jspInit()
The jspInit() method is invoked when the JSP page is initialized.
Methods inherited from interface javax.servlet.Servlet
destroy, getServletConfig, getServletInfo, init, service
Method Detail
jspInit
public void jspInit()
The jspInit() method is invoked when the JSP page is initialized. It is the responsibility of the JSP implementation (and of the class mentioned by the extends attribute, if present) that at this point invocations to the getServletConfig() method will return the desired value. A JSP page can override this method by including a definition for it in a declaration element. A JSP page should redefine the init() method from Servlet.
jspDestroy
public void jspDestroy()
The jspDestroy() method is invoked when the JSP page is about to be destroyed. A JSP page can override this method by including a definition for it in a declaration element. A JSP page should redefine the destroy() method from Servlet.
javax.servlet.jsp
Interface HttpJspPage
All Superinterfaces:
JspPage, Servlet
public interface HttpJspPage extends JspPage
The HttpJspPage interface describes the interaction that a JSP Page Implementation Class must satisfy when using the HTTP protocol.
The behaviour is identical to that of the JspPage, except for the signature of the _jspService method, which is now expressible in the Java type system and included explicitly in the interface.
Method Summary
void _jspService(HttpServletRequest request, HttpServletResponse response)
The _jspService()method corresponds to the body of the JSP page.
Methods inherited from interface javax.servlet.jsp.JspPage
jspDestroy, jspInit
Methods inherited from interface javax.servlet.Servlet
destroy, getServletConfig, getServletInfo, init, service
Method Detail
_jspService
public void _jspService(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,
IOException
The _jspService()method corresponds to the body of the JSP page. This method is defined automatically by the JSP container and should never be defined by the JSP page author.
If a superclass is specified using the extends attribute, that superclass may choose to perform some actions in its service() method before or after calling the _jspService() method. See using the extends attribute in the JSP_Engine chapter of the JSP specification.
Parameters:
request - Provides client request information to the JSP.
response - Assists the JSP in sending a response to the client.
Throws:
ServletException - Thrown if an error occurred during the processing of the JSP and that the container should take appropriate action to clean up the request.
IOException - Thrown if an error occurred while writing the response for this page.
Interface Servlet
All Known Implementing Classes:
GenericServlet, HttpServlet
public interface Servlet
Defines methods that all servlets must implement.
A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol.
To implement this interface, you can write a generic servlet that extends javax.servlet.GenericServlet or an HTTP servlet that extends javax.servlet.http.HttpServlet.
This interface defines methods to initialize a servlet, to service requests, and to remove a servlet from the server. These are known as life-cycle methods and are called in the following sequence:
1. The servlet is constructed, then initialized with the init method.
2. Any calls from clients to the service method are handled.
3. The servlet is taken out of service, then destroyed with the destroy method, then garbage collected and finalized.
In addition to the life-cycle methods, this interface provides the getServletConfig method, which the servlet can use to get any startup information, and the getServletInfo method, which allows the servlet to return basic information about itself, such as author, version, and copyright.
Method Summary
void destroy()
Called by the servlet container to indicate to a servlet that the servlet is being taken out of service.
ServletConfig getServletConfig()
Returns a ServletConfig object, which contains initialization and startup parameters for this servlet.
java.lang.String getServletInfo()
Returns information about the servlet, such as author, version, and copyright.
void init(ServletConfig config)
Called by the servlet container to indicate to a servlet that the servlet is being placed into service.
void service(ServletRequest req, ServletResponse res)
Called by the servlet container to allow the servlet to respond to a request.
Method Detail
init
public void init(ServletConfig config)
throws ServletException
Called by the servlet container to indicate to a servlet that the servlet is being placed into service.
The servlet container calls the init method exactly once after instantiating the servlet. The init method must complete successfully before the servlet can receive any requests.
The servlet container cannot place the servlet into service if the init method
1. Throws a ServletException
2. Does not return within a time period defined by the Web server
Parameters:
config - a ServletConfig object containing the servlet's configuration and initialization parameters
Throws:
ServletException - if an exception has occurred that interferes with the servlet's normal operation
See Also:
UnavailableException, getServletConfig()
getServletConfig
public ServletConfig getServletConfig()
Returns a ServletConfig object, which contains initialization and startup parameters for this servlet. The ServletConfig object returned is the one passed to the init method.
Implementations of this interface are responsible for storing the ServletConfig object so that this method can return it. The GenericServlet class, which implements this interface, already does this.
Returns:
the ServletConfig object that initializes this servlet
See Also:
init(javax.servlet.ServletConfig)
service
public void service(ServletRequest req,
ServletResponse res)
throws ServletException,
java.io.IOException
Called by the servlet container to allow the servlet to respond to a request.
This method is only called after the servlet's init() method has completed successfully.
The status code of the response always should be set for a servlet that throws or sends an error.
Servlets typically run inside multithreaded servlet containers that can handle multiple requests concurrently. Developers must be aware to synchronize access to any shared resources such as files, network connections, and as well as the servlet's class and instance variables. More information on multithreaded programming in Java is available in the Java tutorial on multi-threaded programming.
Parameters:
req - the ServletRequest object that contains the client's request
res - the ServletResponse object that contains the servlet's response
Throws:
ServletException - if an exception occurs that interferes with the servlet's normal operation
java.io.IOException - if an input or output exception occurs
getServletInfo
public java.lang.String getServletInfo()
Returns information about the servlet, such as author, version, and copyright.
The string that this method returns should be plain text and not markup of any kind (such as HTML, XML, etc.).
Returns:
a String containing servlet information
destroy
public void destroy()
Called by the servlet container to indicate to a servlet that the servlet is being taken out of service. This method is only called once all threads within the servlet's service method have exited or after a timeout period has passed. After the servlet container calls this method, it will not call the service method again on this servlet.
This method gives the servlet an opportunity to clean up any resources that are being held (for example, memory, file handles, threads) and make sure that any persistent state is synchronized with the servlet's current state in memory.
---------------------------------------------------------------
javax.servlet.jsp
Interface JspPage
All Superinterfaces:
Servlet
All Known Subinterfaces:
HttpJspPage
public interface JspPage
extends Servlet
The JspPage interface describes the generic interaction that a JSP Page Implementation class must satisfy; pages that use the HTTP protocol are described by the HttpJspPage interface.
Two plus One Methods
The interface defines a protocol with 3 methods; only two of them: jspInit() and jspDestroy() are part of this interface as the signature of the third method: _jspService() depends on the specific protocol used and cannot be expressed in a generic way in Java.
A class implementing this interface is responsible for invoking the above methods at the appropriate time based on the corresponding Servlet-based method invocations.
The jspInit() and jspDestroy() methods can be defined by a JSP author, but the _jspService() method is defined automatically by the JSP processor based on the contents of the JSP page.
_jspService()
The _jspService()method corresponds to the body of the JSP page. This method is defined automatically by the JSP container and should never be defined by the JSP page author.
If a superclass is specified using the extends attribute, that superclass may choose to perform some actions in its service() method before or after calling the _jspService() method. See using the extends attribute in the JSP_Engine chapter of the JSP specification.
The specific signature depends on the protocol supported by the JSP page.
public void _jspService(ServletRequestSubtype request,
ServletResponseSubtype response)
throws ServletException, IOException;
Method Summary
void jspDestroy()
The jspDestroy() method is invoked when the JSP page is about to be destroyed.
void jspInit()
The jspInit() method is invoked when the JSP page is initialized.
Methods inherited from interface javax.servlet.Servlet
destroy, getServletConfig, getServletInfo, init, service
Method Detail
jspInit
public void jspInit()
The jspInit() method is invoked when the JSP page is initialized. It is the responsibility of the JSP implementation (and of the class mentioned by the extends attribute, if present) that at this point invocations to the getServletConfig() method will return the desired value. A JSP page can override this method by including a definition for it in a declaration element. A JSP page should redefine the init() method from Servlet.
jspDestroy
public void jspDestroy()
The jspDestroy() method is invoked when the JSP page is about to be destroyed. A JSP page can override this method by including a definition for it in a declaration element. A JSP page should redefine the destroy() method from Servlet.
javax.servlet.jsp
Interface HttpJspPage
All Superinterfaces:
JspPage, Servlet
public interface HttpJspPage extends JspPage
The HttpJspPage interface describes the interaction that a JSP Page Implementation Class must satisfy when using the HTTP protocol.
The behaviour is identical to that of the JspPage, except for the signature of the _jspService method, which is now expressible in the Java type system and included explicitly in the interface.
Method Summary
void _jspService(HttpServletRequest request, HttpServletResponse response)
The _jspService()method corresponds to the body of the JSP page.
Methods inherited from interface javax.servlet.jsp.JspPage
jspDestroy, jspInit
Methods inherited from interface javax.servlet.Servlet
destroy, getServletConfig, getServletInfo, init, service
Method Detail
_jspService
public void _jspService(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,
IOException
The _jspService()method corresponds to the body of the JSP page. This method is defined automatically by the JSP container and should never be defined by the JSP page author.
If a superclass is specified using the extends attribute, that superclass may choose to perform some actions in its service() method before or after calling the _jspService() method. See using the extends attribute in the JSP_Engine chapter of the JSP specification.
Parameters:
request - Provides client request information to the JSP.
response - Assists the JSP in sending a response to the client.
Throws:
ServletException - Thrown if an error occurred during the processing of the JSP and that the container should take appropriate action to clean up the request.
IOException - Thrown if an error occurred while writing the response for this page.
Template method pattern
In software engineering, the template method pattern is a design pattern. It is a behavioral pattern, and is unrelated to C++ templates.
Template method pattern in pdf
Template method pattern
Java Design Patterns At a Glance
---------------------------------------------------------
Usage
The template method is used to:
* let subclasses implement (through method overriding) behaviour that can vary
* avoid duplication in the code: you look for the general code in the algorithm, and implement the variants in the subclasses
* control at what point(s) subclassing is allowed.
The control structure (inversion of control) that is the result of the application of a template pattern is often referred to as the Hollywood Principle: "Don't call us, we'll call you." Using this principle, the template method in a parent class controls the overall process by calling subclass methods as required. This is shown in the following Java example:
Example
/**
* An abstract class that is common to several games in
* which players play against the others, but only one is
* playing at a given time.
*/
abstract class Game {
protected int playersCount;
abstract void initializeGame();
abstract void makePlay(int player);
abstract boolean endOfGame();
abstract void printWinner();
/* A template method : */
final void playOneGame(int playersCount) {
this.playersCount = playersCount;
initializeGame();
int j = 0;
while (!endOfGame()) {
makePlay(j);
j = (j + 1) % playersCount;
}
printWinner();
}
}
//Now we can extend this class in order to implement actual games:
class Monopoly extends Game {
/* Implementation of necessary concrete methods */
void initializeGame() {
// Initialize money
}
void makePlay(int player) {
// Process one turn of player
}
boolean endOfGame() {
// Return true of game is over according to Monopoly rules
}
void printWinner() {
// Display who won
}
/* Specific declarations for the Monopoly game. */
// ...
}
class Chess extends Game {
/* Implementation of necessary concrete methods */
void initializeGame() {
// Put the pieces on the board
}
void makePlay(int player) {
// Process a turn for the player
}
boolean endOfGame() {
// Return true if in Checkmate or Stalemate has been reached
}
void printWinner() {
// Display the winning player
}
/* Specific declarations for the chess game. */
// ...
}
-----------------
class TestClient{
psvm()
{
Game obj=new Chess();
int playersCount=5;
obj.playOneGame(playersCoun);
}
}
Template method pattern in pdf
Template method pattern
Java Design Patterns At a Glance
---------------------------------------------------------
Usage
The template method is used to:
* let subclasses implement (through method overriding) behaviour that can vary
* avoid duplication in the code: you look for the general code in the algorithm, and implement the variants in the subclasses
* control at what point(s) subclassing is allowed.
The control structure (inversion of control) that is the result of the application of a template pattern is often referred to as the Hollywood Principle: "Don't call us, we'll call you." Using this principle, the template method in a parent class controls the overall process by calling subclass methods as required. This is shown in the following Java example:
Example
/**
* An abstract class that is common to several games in
* which players play against the others, but only one is
* playing at a given time.
*/
abstract class Game {
protected int playersCount;
abstract void initializeGame();
abstract void makePlay(int player);
abstract boolean endOfGame();
abstract void printWinner();
/* A template method : */
final void playOneGame(int playersCount) {
this.playersCount = playersCount;
initializeGame();
int j = 0;
while (!endOfGame()) {
makePlay(j);
j = (j + 1) % playersCount;
}
printWinner();
}
}
//Now we can extend this class in order to implement actual games:
class Monopoly extends Game {
/* Implementation of necessary concrete methods */
void initializeGame() {
// Initialize money
}
void makePlay(int player) {
// Process one turn of player
}
boolean endOfGame() {
// Return true of game is over according to Monopoly rules
}
void printWinner() {
// Display who won
}
/* Specific declarations for the Monopoly game. */
// ...
}
class Chess extends Game {
/* Implementation of necessary concrete methods */
void initializeGame() {
// Put the pieces on the board
}
void makePlay(int player) {
// Process a turn for the player
}
boolean endOfGame() {
// Return true if in Checkmate or Stalemate has been reached
}
void printWinner() {
// Display the winning player
}
/* Specific declarations for the chess game. */
// ...
}
-----------------
class TestClient{
psvm()
{
Game obj=new Chess();
int playersCount=5;
obj.playOneGame(playersCoun);
}
}
Subscribe to:
Posts (Atom)