Saturday, December 22, 2007

Using the Java Standard Tag Library (JSTL) in a JSP Page

There are four tag libraries that make up the JSTL; see the javax.servlet.jsp.jstl.* packages for examples that use these tag libraries. JSTL is not yet a standard part of a JSP container. Hence, in order to use the JSTL in a web application, you must include a copy the JSTL library code in the WEB-INF directory of your web application. These files are available in the Web Services Developer Pack, which can be download from http://java.sun.com/webservices/webservicespack.html.
A tag library has two parts: a Tag Library Descriptor (TLD) file and a JAR file. The following ant elements copy the TLD files from the Web Services Developer Pack into WEB-INF/tld and the JAR files into WEB-INF/lib. These elements should be added to the build target in your build.xml file:

<%-- Copy TLD files from WSDP installation --%>






<%-- Copy JSTL jar files from WSDP installation --%>









In order for a JSP page to use the JSTL, it must declare it's use on the page using the taglib directive. Here's an example that declares the use of all four JSTL tag libraries:
<%-- Core --%>
<%@ taglib uri="/WEB-INF/tld/c-rt.tld" prefix="c_rt" %>

<%-- I18N Formatting --%>
<%@ taglib uri="/WEB-INF/tld/fmt-rt.tld" prefix="fmt_rt" %>

<%-- SQL --%>
<%@ taglib uri="/WEB-INF/tld/sql-rt.tld" prefix="sql_rt" %>

<%-- XML --%>
<%@ taglib uri="/WEB-INF/tld/x-rt.tld" prefix="x_rt" %>

Sample Java Code To Create Custom Tag

A custom tag handler must implement the Tag interface. This interface is implemented by many convenient support classes from which a custom tag handler can extend. As a JSP page is executed and the custom tag is encountered, the doStartTag() of the tag handler is executed. If that method does not throw an exception, the tag handler's doEndTag() method is then called.
The JSP container may create many instances of the tag handler but guarantees that an instance services only one request at a time. A JSP container also typically reuses a tag handler instance and so instance variables should be appropriately reset if necessary.

This example implements a tag handler for the simplest type of tag - - one without attributes or a body. This custom tag simply prints the current time and day.

package com.mycompany;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

// This tag simply emits the current date and time.
public class MyTagHandler extends TagSupport {
public int doStartTag() throws JspException {
try {
// Print the current date and time
pageContext.getOut().print(""+new java.util.Date());
} catch (java.io.IOException e) {
throw new JspTagException("MyTag: "+e.getMessage());
}
return SKIP_BODY;
}

public int doEndTag() {
return EVAL_PAGE;
}
}

A web application wishing to use the custom tag must not only include the custom tag's class file but also its Tag Library Descriptor (TLD) as well. The TLD is a file that contains information about one or more custom tags and is needed by a JSP container to process pages that use a custom tag. Here's the TLD file (mytaglib.tld) for the custom tag:


"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">

<%-- Version of this tag library; it should have the form 123 or 123.456 --%>
0.96

<%-- The required version of JSP for this tag library --%>
1.2

<%-- The preferred prefix for this tag library --%>
my

<%-- This is the URI that uniquely identifies this tag library.
The URI does not have to exist; it is merely an identifier --%>
http://com.mycompany/taglib/mytaglib

<%-- This name is used by tools to represent this tag library --%>
My Tag Library

This is a description of the tag library.


<%-- Name of tag in this library --%>
simple
com.mycompany.MyTagHandler

<%-- Specify that the tag must not have a body --%>
empty

This is a description of the tag.




Here's an example of a JSP page that uses the custom tag. The TLD file is assumed to be in WEB-INF/tld and the MyTagHandler.class file in WEB-INF/classes/com/mycompany:
<%@ taglib uri="/WEB-INF/tld/mytaglib.tld" prefix="my" %>

Thursday, December 20, 2007

Java Program to Parse an XML File Using SAX

import java.io.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class BasicSax {
public static void main(String[] args) {
// Create a handler to handle the SAX events generated during parsing
DefaultHandler handler = new MyHandler();

// Parse the file using the handler
parseXmlFile("infilename.xml", handler, false);
}

// DefaultHandler contain no-op implementations for all SAX events.
// This class should override methods to capture the events of interest.
static class MyHandler extends DefaultHandler {
}

// Parses an XML file using a SAX parser.
// If validating is true, the contents is validated against the DTD
// specified in the file.
public static void parseXmlFile(String filename, DefaultHandler handler, boolean validating) {
try {
// Create a builder factory
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(validating);

// Create the builder and parse the file
factory.newSAXParser().parse(new File(filename), handler);
} catch (SAXException e) {
// A parsing error occurred; the xml input is not valid
} catch (ParserConfigurationException e) {
} catch (IOException e) {
}
}
}

Wednesday, December 19, 2007

Java Code to convert XML fragment to DOM fragment

// Parses a string containing XML and returns a DocumentFragment
// containing the nodes of the parsed XML.

public static DocumentFragment parseXml(Document doc, String fragment) {
// Wrap the fragment in an arbitrary element
fragment = ""+fragment+"";

try {
// Create a DOM builder and parse the fragment
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

Document d = factory.newDocumentBuilder().parse(
new InputSource(new StringReader(fragment)));

// Import the nodes of the new document into doc so tha they

// will be compatible with doc
Node node = doc.importNode(d.getDocumentElement(), true);

// Create the document fragment node to hold the new nodes
DocumentFragment docfrag = doc.createDocumentFragment();

// Move the nodes into the fragment
while (node.hasChildNodes()) {
docfrag.appendChild(node.removeChild(node.getFirstChild()));
}

// Return the fragment
return docfrag;
} catch (SAXException e) {
// A parsing error occurred; the xml input is not valid
} catch (ParserConfigurationException e) {
} catch (IOException e) {
}
return null;
}

Here's an example that uses the method:
// Obtain an XML document; this method is implemented in
// e510 The Quintessential Program to Create a DOM Document from an XML File
Document doc = parseXmlFile("infilename.xml", false);

// Create a fragment
DocumentFragment frag = parseXml(doc, "hello joe");

// Append the new fragment to the end of the root element
Element element = doc.getDocumentElement();
element.appendChild(frag);

Tuesday, December 18, 2007

Java Program to Play a music file.

//Loading and Playing Midi Audio
try {
// From file
Sequence sequence = MidiSystem.getSequence(new File("midifile"));

// From URL
sequence = MidiSystem.getSequence(new URL("http://hostname/midifile"));

// Create a sequencer for the sequence
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open();
sequencer.setSequence(sequence);

// Start playing
sequencer.start();
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (MidiUnavailableException e) {
} catch (InvalidMidiDataException e) {
}

Monday, December 17, 2007

Java Program to Play Streaming Midi Audio

//Playing Streaming Midi Audio
//Supported audio file formats: mid, rmf
try {
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open();

// From file
InputStream is = new BufferedInputStream(
new FileInputStream(new File("midifile")));

// From URL
is = new BufferedInputStream(
new URL("http://hostname/rmffile").openStream());

sequencer.setSequence(is);

// Start playing
sequencer.start();
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (MidiUnavailableException e) {
} catch (InvalidMidiDataException e) {
}

Sunday, December 16, 2007

Java Code for Playing Streaming Midi Audio

//Supported audio file formats: mid, rmf
try {
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open();

// From file
InputStream is = new BufferedInputStream(
new FileInputStream(new File("midifile")));

// From URL
is = new BufferedInputStream(
new URL("http://hostname/rmffile").openStream());

sequencer.setSequence(is);

// Start playing
sequencer.start();
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (MidiUnavailableException e) {
} catch (InvalidMidiDataException e) {
}

Tuesday, November 27, 2007

Adding, Replacing, Removing, and Renaming a Binding in the Naming Service

try {
// Add a binding.
ctx.bind("Name", new SampleObjectImpl());

// Replace a binding.
ctx.rebind("Name", new SampleObjectImpl());

// Remove a binding.
ctx.unbind("Name");

// Rename a binding.
ctx.rename("Name", "NewSample");
} catch (NamingException e) {
}

Monday, November 26, 2007

Using a URL as a Name to the Initial Context

This example looks up an object from the naming service by using a URL as a name.
try {
Object obj = new InitialContext().lookup("iiop://localhost/Sample");
} catch (NamingException e) {
}

Wednesday, November 21, 2007

Looking Up an Object from the Naming Service

This example looks up an object from the naming service.
try {
Object obj = ctx.lookup("Sample");
} catch (NamingException e) {
}

Creating an Initial Context to the Naming Service

This example uses the JNDI/COS naming service provider to connect to the local tnameserv.
String url = "iiop://localhost/";
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.cosnaming.CNCtxFactory");
env.put(Context.PROVIDER_URL, url);
try {
Context ctx = new InitialContext(env);
} catch (NamingException e) {
}

Thursday, November 15, 2007

Listing a Context in the Naming Service

This example lists a context in the naming service.
try {
NamingEnumeration enum = ctx.list("child");
while (enum.hasMore()) {
NameClassPair entry = (NameClassPair)enum.next();
process(entry);
}
} catch (NamingException e) {
}

Sunday, October 28, 2007

Calling a Stored Procedure in a Database

This example demonstrates how to call stored procedures with IN, OUT, and IN/OUT parameters.
CallableStatement cs;
try {
// Call a procedure with no parameters
cs = connection.prepareCall("{call myproc}");
cs.execute();

// Call a procedure with one IN parameter
cs = connection.prepareCall("{call myprocin(?)}");

// Set the value for the IN parameter
cs.setString(1, "a string");

// Execute the stored procedure
cs.execute();

// Call a procedure with one OUT parameter
cs = connection.prepareCall("{call myprocout(?)}");

// Register the type of the OUT parameter
cs.registerOutParameter(1, Types.VARCHAR);

// Execute the stored procedure and retrieve the OUT value
cs.execute();
String outParam = cs.getString(1); // OUT parameter

// Call a procedure with one IN/OUT parameter
cs = connection.prepareCall("{call myprocinout(?)}");

// Register the type of the IN/OUT parameter
cs.registerOutParameter(1, Types.VARCHAR);

// Set the value for the IN/OUT parameter
cs.setString(1, "a string");

// Execute the stored procedure and retrieve the IN/OUT value
cs.execute();
outParam = cs.getString(1); // OUT parameter
} catch (SQLException e) {
}

Saturday, October 20, 2007

Connecting to a SQLServer Database

This example connects to a SQLServer database using the NetDirect JDBC driver. For information about this driver, see e232 Getting JDBC Drivers for a Database.
Connection connection = null;
try {
String driverName = "com.jnetdirect.jsql.JSQLDriver"; // NetDirect JDBC driver
String serverName = "127.0.0.1";
String portNumber = "1433";
String mydatabase = serverName + ":" + portNumber;
String url = "jdbc:JSQLConnect://" + mydatabase; // a JDBC url
String username = "username";
String password = "password";

// Load the JDBC driver
Class.forName(driverName);

// Create a connection to the database
connection = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
// Could not find the database driver
} catch (SQLException e) {
// Could not connect to the database
}

Connecting to a MySQL Database

This example connects to a MySQL database using the MM JDBC driver for MySQL. You need to have an account in MySQL database to run this example. To create an account, you can connect to MySQL database on your platform as root, and run the following command:
mysql> GRANT ALL PRIVILEGES ON *.* TO username@localhost
IDENTIFIED BY 'password' WITH GRANT OPTION;


Connection connection = null;
try {
// Load the JDBC driver
String driverName = "org.gjt.mm.mysql.Driver"; // MySQL MM JDBC driver
Class.forName(driverName);

// Create a connection to the database
String serverName = "localhost";
String mydatabase = "mydatabase";
String url = "jdbc:mysql://" + serverName + "/" + mydatabase; // a JDBC url
String username = "username";
String password = "password";
connection = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
// Could not find the database driver
} catch (SQLException e) {
// Could not connect to the database
}

Connecting to an Oracle Database

This example uses an Oracle JDBC driver to connect to an Oracle database instance located at 128.0.0.0:1521 with an sid called mydatabase.

Connection connection = null;
try {
// Load the JDBC driver
String driverName = "oracle.jdbc.driver.OracleDriver";
Class.forName(driverName);

// Create a connection to the database
String serverName = "127.0.0.1";
String portNumber = "1521";
String sid = "mydatabase";
String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
String username = "username";
String password = "password";
connection = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
// Could not find the database driver
} catch (SQLException e) {
// Could not connect to the database
}

Monday, October 15, 2007

Listing All Loaded JDBC Drivers

This example lists all loaded JDBC drivers and gets information about each one.

List drivers = Collections.list(DriverManager.getDrivers());
for (int i=0; i < drivers.size(); i++) {
Driver driver = (Driver)drivers.get(i);

// Get name of driver
String name = driver.getClass().getName();

// Get version info
int majorVersion = driver.getMajorVersion();
int minorVersion = driver.getMinorVersion();
boolean isJdbcCompliant = driver.jdbcCompliant();
}

Thursday, October 11, 2007

Loading a JDBC Driver

Before a connection to a database can be established, the JDBC driver for that database must be loaded. Drivers automatically register themselves with the JDBC system when loaded. There are two ways to load a JDBC driver. The first is to specify the driver or colon-separated list of drivers on the command line:
> java -Djdbc.drivers=com.company1.Driver:com.company2.Driver MyApp


The second, and recommended method, is to call Class.forName() within the code:
try {
// Load the JDBC driver
String driverName = "org.gjt.mm.mysql.Driver";
Class.forName(driverName);
} catch (ClassNotFoundException e) {
// Could not find the driver
}