Sunteți pe pagina 1din 23

Right-Clicks on a Single Button Mouse

Those of us with a two- or three-button mouse are familiar with the idea of a right-click, but how
can you detect which button is pressed from your Java code? And to keep your applet or
application platform independent, how can you cater for similar functionality with a one-button
mouse? Fortunately, the InputEvent modifier flags serve double duty, so that clicking the right
button or holding down the Alt key while clicking the left button, have the same effect. By masking
the event modifiers in a mouseClicked method, you can permit the user to press Shift, Ctrl, Meta
or Alt keys.

import java.awt.*;
import java.awt.event.*;
public class YourClass implements MouseListener {
// Your constructors and methods here
public void mouseClicked(MouseEvent ev) {
int mask = InputEvent.BUTTON1_MASK - 1;
int mods = ev.getModifiers() & mask;
if (mods == 0) {
// Left button clicked
}
else {
// Right button clicked
}
}
}
Note that this code does not distinguish between the right and center buttons on a three button
mouse, but it could be extended to do so.

How to Access Cookies Set at the Client Side


Class javax.servlet.http.cookies can be used to access cookies on the client side. The following
code demonstrates this technique. The code also checks for the cookie names in order to access
the desired one.

boolean bcookiefound = false;


Cookie[] cookies = request.getCookies();
for(int nIndex=0;nIndex < cookies.length;nIndex++)
{
if(cookies[nIndex].getName().equals(“MyCookie”))
{
bcookiefound = true;
//desired cookie found, use it
}
}
if(bcookiefound == false)
{
//cookie not found.
}
Use an Adapter Class To Provide Empty Implementations For
Javabean Interfaces
Like many high-level, abstract, and portable concepts, EJB spec has its downsides. One of them
is the very generality that makes beans so portable. Interfaces javax.ejb.EntityBean and
javax.ejb.SessionBean declare quite a few methods and most of them are not used by simple
bean implementation. Yet developers must provide empty implementations for all these methods.
As with many generic interfaces (Swing, etc.), one possible solution is an adapter class. This
class would "implement" the respective interface by providing empty or default implementations
for all the methods declared in the interface. For instance:

public class EntityBeanAdapter implements javax.ejb.EntityBean {


EntityContext myContext;

public void ejbActivate() throws RemoteException {}


public void ejbLoad() throws RemoteException {}
public void ejbStore() throws RemoteException {}
public void ejbPassivate() throws RemoteException {}
public void ejbRemove() throws RemoteException {}

public void setEntityContext(EntityContext _ctxt) {


myContext = _ctxt;
}

public EntityContext getEntityContext() {


return myContext;
}

public void unsetEntityContext() {


myContext = null;
}
}

This process would be similar for the SessionBean.

Now, the implementations can just extend these adapters instead of implementing the EntityBean
and SessionBean interfaces directly. Like:

public class AccountBean extends EntityBeanAdapter {


... the code
}

If any of the callback methods are needed, they can be overridden here. CAUTION: As with all
adapters, if you misspell the method while attempting to override it, the compiler won't bark, but
the methods will never get invoked. So, check your spelling!

Convert Your Data to Decimal/Integer Value


Generally speaking, the data you're being asked to process most likely has not been input in the
format you need. It comes in hexadecimal, octal, or even in binary formats.
Converting this data into decimal/integer format can be tedious. Fortunately, the Java API
provides a method that performs this conversion without any overhead for the developer.

The method takes two arguments. The first argument is the string value that needs to be
converted to integer format. The second argument establishes the type of the argument—whether
it is in hexadecimal, octal, or binary format. In the following code, the syntax is
Integer.parseInt(stringValue,radixValue);. stringValue is the value to be converted and radixValue
is the value for hexadecimal, octal, or binary as 16, 8, or 2 respectively:

String hexVal = "A"; //Hexadecimal


String octVal = "81"; //Octal
String binVal = "1101"; //Binary

System.out.println("Hex to Decimal. Hex = "+ hexVal + ",


Decimal = "+Integer.parseInt(hexVal,16);
System.out.println("Octal to Decimal. Hex = "+ octVal + ",
Decimal = "+Integer.parseInt(octVal,8);
System.out.println("Binary to Decimal. Hex = "+ binVal + ",
Decimal = "+Integer.parseInt(binVal,2);
The result is the conversion from the respective formats to decimal value

Activate Your Applets


Did you ever feel the urge to use a nice Java class you just wrote as an ActiveX object on your
Windows machine? Good news: you can do it in three easy steps. First, make sure you've got the
latest build of the Microsoft VM on the target machine (check http://www.microsoft.com/java/).
Second, copy your .class file to the LIB or TRUSTLIB directory. Third, run the JAVAREG utility
(use Start/Find/Find Files if you're not sure where it is) as follows:
JAVAREG /register /class:<JavaClass> /progid:<ProgID> <JavaClass> is the name of your class,
and <ProgID> can be anything, but preferably the same--it's the object name you'll have to pass
to a function like CreateObject later on.

And that's it! The nice thing is that this will work for any Java class that will run on the Microsoft
VM, and not just classes created with Microsoft development tools. If you want to get rid of your
ActiveX object at any time, use JAVAREG with the /unregister switch.

Putting out the Trash Using the gc() Call


The gc() call on the Java Virtual Machine's garbage collector is often misunderstood. One of the
reasons Java is such an easy language to program in is that it takes the burden of memory
management away from the developer. Specifically, you never have to worry about deallocating
memory that is held by resources in your running program. That's where the garbage collector
comes in: you set your object to null and the garbage collector collects it. Simple. Or is it?

When exactly does the garbage collector collect unused memory? It doesn't collect it when you
set the object to null; it collects memory periodically or when the system is running low on
resources. So do you have any control over when the memory is freed? Java does provide a
method gc() that may be used as follows:
1. public void freeMemory () {
2.
3. String myString = new String("Free Me");
4.
5.
6.
7. // Do stuff with myString
8.
9.
10.
11. myString = null;
12.
13. Runtime rt = Runtime.getRuntime();
14.
15. rt.gc();
16.
17.}
18.

On line 2, the String "Free Me" is created and this memory is assigned to the object myString. On
Line 6, the object is set to null, so that it will be collected when the garbage collector runs. On
Line 7, an instance of the current runtime is obtained and on 8, the call to gc() is made.
Please note that the call on Line 8 does not cause the garbage to be collected. It is merely a hint
to the VM to free the memory as soon as it can. Also, when the garbage collector runs, it may not
free the memory for the object that you just released.
So is there any use for setting the object to null and calling gc()? Yes, because you are helping
the garbage collector free up unused memory and you are also telling it to do this ASAP. If the
object myString ate up a lot of memory (instead of what is occupied by "Free Me"), you would
definitely want to invoke gc() before you allocate more memory.
However, overusing the gc()call can be detrimental because you will be asking the garbage
collector to run before it is normally scheduled to run. When the garbage collector runs, it
consumes resources from the same pool used by your applications. Using this runtime call
requires careful thought and programmers need to be aware that the memory is not freed
immediately. You cannot force the garbage collector to pick up the trash at specific times. You
can only politely ask it to do so when it can.

Formats for Uploading Files


When you transfer files from Windows to the Macintosh, the files become DOS text files. This can
be a problem if you convert movies to Java on a Windows computer and then transfer the files to
a Macintosh file server. For reliable results when uploading files from Windows, upload files as
raw binary files instead of text files.

Allocating Memory Before Calling a Function


Suppose you want to pass an object to a method and also want to allocate the object into that
method. If you pass the object as it is, it will not work because the memory that the object points
to changes. To get around this, wrap this object into another object and pass that object as a
parameter to the function.
Object.hashCode() and Object.equals()
The Object.hashCode() method returns a number that is effectively random. This number is also
implementation- and instance-dependent. This has a couple consequences:

1 - The order of iteration for elements in a Hashtable will be unpredictable, and will generally
differ from one program invocation to the next.

2 - A class that overrides Object.equals() must also override Object.hashCode(). It is safe, if


inefficient, if the hashCode() method returns the same value for unequal objects. It is unsafe if the
hashCode() method returns different values for two objects that are, in fact, equal.

Solution: If a repeatable order of enumeration over the elements in a Hashtable is important to


your program, then any object used as a key in the Hashtable should have a class-specific
hashCode method. This hashCode method should return a value computed from data fields of
the object. If any of your classes define an equals method, they must also define a hashCode
method. This means that for any two objects a,b of that class, a.equals(b) implies that
a.hashCode() == b.hashCode(). Note that hashCode should not depend on any mutable property.
If an object’s hashCode value changes, that object is very likely to become irrevocably lost.

Helping the Java Garbage Collector


When you create an object in Java, such as in the following code:
Button b = new Button();
Java creates a new Button object in memory and sets the value of variable b so that it points to
this object on the heap. It also sets a reference count to the object. When you are finished with
the object set the reference variable to null. This reduces the reference count and, when the
reference count reaches zero, the object's memory can be reclaimed by Java's garbage collector.
Remember to set unused object references to null:
b = null;
to help out the Java garbage collector.

How to Pass Parameters from a Java Applet to an HTML File


Sometimes you need to pass parameters from an applet to an HTML file. For instance, you may
want to detect, using an applet, the IP address of the viewer when they are trying to access your
page and send them to a HTML page that will dynamically use it.

applet_test.java: This is the sample Java applet that returns the hostname of the machine and the
IP address associated with that hostname.

--- applet_test.java ---


import java.applet.Applet;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class applet_test extends Applet {
private InetAddress addr = null;
public void init() {
try {
addr = InetAddress.getLocalHost();
}
catch (UnknownHostException e) {
System.exit(0);
}
}
public InetAddress getLHost() {
return addr;
}
}
test.html: The sample HTML file test.html calls a Java applet (applet_test.class) and gets the
getLHost() parameter from this applet:

--- test.html ---


<html>
<body>
<APPLET CODE=applet_test.class Width=0 Height=0></APPLET>
<script type="text/javascript">
<!--
document.write(document.applets[0].getLHost());
//-->
</script>
</body>
</html>

Modifying Client JavaScript Code at Runtime


You can make new tags/components using JavaScript blocks. Simply include a script iterating
through all the script blocks in your page:

<script language="javascript">
function writeComponent(){
var scriptblocks = document.getElementsByTagName("script");
for (i=0;i < scriptblocks.length;i++){
//iterate through all the script blocks
if (scriptblocks[i].innerHTML== "writeComponent()"){
//initialize your component as javascript object
var classname = scriptblocks[i].getAttribute("classname");
eval("var component = new " + classname + "()");
//the JsObject should implement a getElement() function
//so is can be retrieved and replace the scriptblock element
var parent = scriptblocks[i].parentNode;
parent.replaceChild(component.getElement(),scriptblocks[i]);
var attribs = scriptblocks[i].attributes;
//you can copy attribute values in your constructor
//or set the style of the component element
}
}
}
</script>

<html> etc...
<script language="javascript"
classname="myCompClass">writeComponent()</script>
As soon as the browser renders the scriptblock, the function is called and the browser replaces
the script block with whatever component you've written.

Compressed Output From Servlet


The Java servlet below demonstrates how to use compressed output from servlets. You can
compress big chunks of data before sending and they will be decompressed on the fly in the
browser.

Any browser supports, by default, different file formats. The most known and usable are gif and
jpg of course. But browsers can also support gzip files, and in your servlets, you can detect which
formats are supported. So check compression support by analyzing the request header and use
Java's GZIP support for data compression.

import java.io.*;
import java.util.zip.*;
import java.lang.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class GzipServlet extends HttpServlet {

public void doGet (HttpServletRequest req,


HttpServletResponse res)
throws ServletException, IOException
{
doPost(req,res);
}

public void doPost (HttpServletRequest req,


HttpServletResponse res)
throws ServletException, IOException
{

String encoding=req.getHeader("Accept-Encoding");
boolean canGzip=false;

if (encoding!=null)
if (encoding.indexOf("gzip")>=0)
canGzip=true;

if (canGzip)
{
res.setHeader("Content-Encoding","gzip");
OutputStream o=res.getOutputStream();
GZIPOutputStream gz=new GZIPOutputStream(o);
String bigStuff="";
bigStuff+="<html>";
bigStuff+="<br>this was compressed";
bigStuff+="</html>";
gz.write(bigStuff.getBytes());
gz.close();
o.close();

}
else // no compression
{
PrintWriter out=res.getWriter();
res.setContentType("text/html");

out.println("<html>");
out.println("<br>no compression here");
out.println("</html>");

out.flush();
out.close();
}

What are Servlets?


All Java programmers probably know what Java applets are and how they differ from Java
applications. After all applets were Java's gateway into the Internet. Servlets are Java's entry into
the server side of the client-server paradigm.

Servlets are Java's server-side counterpart of applets and are also known as "faceless applets."
Just as applets run in Web browsers, servlets run in Web servers. Unlike applets, servlets have
no standard user interface. In JDK 1.2, Java has an extension package, javax.servlet that defines
the Servlet API. The most common use for servlets is as a replacement for CGI scripts.

A servlet's main purpose in life is to server up HTML to the client, most often through the HTTP
protocol. Servlets are created, managed, and destroyed by the Web server that they run in. They
are known only in the context of a Web server. Some of the popular Web servers that support
servlets are Microsoft IIS, Netscape Enterprise, Apache server, and the Sun Web server.

Servlets help support thin clients. Computation-intensive functionality can be moved over to the
server side and accessed via servlets instead of forcing the client to download the necessary
classes to the client side.

Middle Tier Code Optimization With Java Reflection Package


In Web based programming, we usually check querystring parameters in middle tier java objects
and do tedious, if not long, checks via if/else, to perform appropriate action or instantiate classes.
A good workaround is to use Java reflection (java.lang.reflect). Class methods, like getMethods[]
or getFields[], invoke particular methods based on http querystring params, like
Method.invoke(...).

Here is an example java codelet:


//get Class info of your object say 'a'
Class c = a.getClass();

//to dynamically get Object/fields based on HTTP


querystring namevalue pair, say 'requestParam'

Field f = c.getField(requestParam);

// or else 'invoke' a particular method vis a vis


requestParam

Method[] theMethods = c.getMethods();


String result = (String) theMethods[0].invoke
(requestParam, null);

Mutual Exclusion in Servlets


While writing portals using servlets, it is possible for two users to enter the same login name and
press request at exactly the same time. It’s also possible for both users to be allocated the same
login name, which may create problems. To avoid this, just use the keyword “synchronized” in the
function prototype where you are actually making the connection with the database. For example:

public synchronized void yourfunction()


{
// code goes here
}

This will guarantee mutual exclusion and will NEVER give the same username to two different
users, even if the request arrives at exactly the same instant.

Share Information with Other Web Resources Using


ServletContext
The Servlet API provides the class javax.servlet.ServletContext, which has methods that work
with data stored in context. Any servlet can store Java objects in that context and other servlets
can use them. The objects are stored with a String key for uniqueness.

Here's how it works:

1. Use setAttribute(String key, Object value) to store an attribute in context. key is the name
of the attribute and value is the Java object to be stored.
2. Use getAttribute(String key) to retreive the Java object corresponding to the value of key
in context. If no object is found, null is returned.
3. Remove attributes from context using remove(String key).

ServletContext can be used in other ways besides data sharing—for instance, working with
RequestDispatcher or logging into the servlet log file.

Configure the Behavior of Servlets While They Are Loaded


Servlets can be configured using the initialization parameter. These parameters can be anything
like username, password, URL, etc for accessing a database connection, the location of the
configuration file, etc.
Assume the servlet is MyServlet.class and the parameter to pass is param1. The following steps
show how to use param1, with MyServlet.

1. Add the following entry in web.xml:


2.
3. <servlet>
4. <servlet-name>MyServlet</servlet-name>
5. <display-name>MyServlet</display-name>
6. <servlet-class>MyServlet</servlet-class>
7. <init-param>
8. <param-name>param1</param-name>
9. <param-value>It is value of param1</param-value>
10. </init-param>
11. </servlet>
12. This servlet code reads the initialization parameters from the ServletConfig class:
13.
14. javax.servlet.ServletConfig config = getServletConfig();
15. String value1 = config.getInitParameter("param1");
Place this code in the init() method of the servlet so that the parameters are read while the servlet
loads and sets global variables for use by the service method each time.
You can pass as many parameters this way with a different <init-param> element for each param.

How to Read Client-Side Cookies From a Servlet


Reading cookies from a servlet is easy. You can gain access to any cookies sent by the browser
from the javax.servlet.http.HttpServletRequest passed to the servlet's doGet, doPost, etc
methods. HttpServletResponse offers a method, and Cookies[] getCookies() returns an array of
Cookie objects.

// Check for cookies


Cookie[] cookies = request.getCookies();

// Check to see if any cookies exists


if (cookies != null)
{
for (int i =0; i< cookies.length; i++)
{
Cookie aCookie = cookies[i];
System.out.println (“Name : “ + aCookie.getName());
System.out.println (“Value: “ + aCookie.getValue());
}
}

Pushing an Applet from a Servlet


When trying to use an applet inside a servlet using the applet tag:

out.println("<applet code=appletname>" + "</applet>")


Two things must be kept in mind:

1.You must include the codebase in the <applet> otherwise the applet class will not be located.
So use something like out.println("<applet code=appletname" + "codebase='/'>" + "</applet>")for
the home directory.
2.You must place the applet class along with the HTML documents. GIF and JPG problems occur
when you keep the applet class in the directory, where the other java classes are usually kept, or
with the servlet classes—then the client's browser is not able to locate the applet class.

Storing Request-specific Data Without Using ServletRequest


There are times when you need to store request-specific attributes (pieces of data that must be
available to one specific http-request during the lifetime of that http-request) in order to retrieve
them later.

This is easy—if you have access to the ServletRequest instance. You simply use its methods,
getAttribute() and setAttribute(), for attribute storage.

But sometimes your code does not provide access to the current request's ServletRequest
instance. One way around this is to modify the parameter-list of methods to pass the
ServletRequest instance all the way down to the method that needs the request-specific
attributes. This would use the ServletRequest's getAttribute() method. However, this refactoring is
not always possible.

Another solution is to use the thread's local memory, because each ServletRequest is executed
in one thread only (it does not switch threads).

First, define a ThreadLocal class and a class holding your data:

class RequestCache extends ThreadLocal


{
protected Object initialValue()
{
return new RequestCacheEntry();
}
}

class RequestCacheEntry
{
HttpServletReqeust mRequest;
// ... or any other member you'd like to store in this class.
}
Then, modify your servlet to set the request-specific data and a public method to retrieve it:

public class MyServlet extends HttpServlet


{
...
private static final RequestCache smReqCache = new RequestCache();

public static RequestCacheEntry getCurrentRequestData()


{
return (RequestCacheEntry)smReqCache.get();
}
...
}
Next, add these pieces of code in your servlet's doGet and/or doPost methods:
public void doGet(HttpServletRequest pRequest, HttpServletResponse
pResponse)
{
RequestCacheEntry reqCacheEntry =
(RequestCacheEntry)smReqCache.get();
reqCacheEntry.mRequest = pRequest;

..
.. do all your servlet stuff :)

reqCacheEntry.mRequest = null;
}
You can call MyServlet.getCurrentRequestData() to obtain your request-specific data anywhere in
your servlet-code where you don't have access to the current HttpServletRequest instance.

Initializing Application Attributes During Context Initialization


Many applications require some of their attributes to be initialized much before the application is
made available to the user or before it can process a request.

Suppose you've got an application with a new version that needs to be present across the
application—but it needs to be initialized beforehand. The approach outlined in this tip eliminates
the process of retrieving that value from the datastore (or permanent storage location) every time
such an initialization is required.

The ServletContextListener interface from the javax.servlet package can perform this operation
for you.

First, you need to register the class that implements this interface as a listener element in the
web.xml. Then, you implement the methods contextInitialized(ServletContextEvent sce) and
contextDestroyed(ServletContextEvent sce) as required.

The class that implements this interface receives notification when the context is initialized, as
well as when it gets destroyed.

Here's a sample code fragment:

public class InitializeData implements ServletContextListener {


public void contextInitialized(ServletContextEvent event) {
ServletContext context = event.getServletContext();
setInitialAttribute(context,"app.version",value);
// value can be either from a properties file or from a datasource
// or any-other source
}

public void contextDestroyed(ServletContextEvent event){


//code that needs to be done when the context is destroyed.
//can be like destroying the thread or closing resources etc.
}
private void setInitialAttribute(ServletContext context,
String initParamName,String initialValue) {
context.setAttribute(initParamName, initialValue);
}

//other methods can also come in


}
The attribute that is set can be retrieved across the application using the
getServletContext().getAttribute("app.version") and used appropriately.

How to Speed Up Data Transfer Between Servlet and Applet


We can speed up the data transfer between servlet and applet in a Web application by
compressing the data transferred between them. The example below demonstrates how this is
done:

Servlet Code:

public void doGet(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException
{
try
{
res.setHeader("Content-Encoding","gzip");
OutputStream out = res.getOutputStream();
GZIPOutputStream gz = new GZIPOutputStream(out);

String data = "Compressed Data";

gz.write(data.getBytes());
gz.close();
out.close();
}
catch(Exception e)
{
System.out.println("In CompressServlet: Exception in doGet");
}
}

//Applet Code:

public class UnCompressApplet extends Applet {

String fromServ = "";

public void start()


{
try
{
readData();
}
catch(Exception e)
{
System.out.println("Exception in start()");
}
}

public void paint(Graphics g)


{
// Display the obtained data
g.drawString("Contents of Servlet Data: " + fromServ, 10, 10);
}

public void readData() throws Exception


{

try
{
GZIPInputStream gz = new GZIPInputStream( getData() );

byte[] buf = new byte[1024];


int len;

while ((len = gz.read(buf)) > 0)

fromServ = new String(buf);

gz.close();
}
catch (IOException e)
{
System.out.println("In UncompressApplet: Exception in readData()");
}

public InputStream getData() throws Exception


{
try{

//URL of the Web Server


String url = "http://localhost:8080/examples/servlet/CompressServlet";

URL postURL = new URL( url );

URLConnection urlCon = null;

urlCon = postURL.openConnection();

urlCon.setDoOutput(true);
urlCon.setDoInput(true);
return urlCon.getInputStream();

}
catch(Exception e)
{
e.printStackTrace();
return null; //something went wrong
}

}//end of getData

}//end of class

HTML Code :

Close ResultSet Object Explicitly Before Closing Connection


when Using Servlets
Most Java programmers close a connection with database directly without closing the ResultSet.
This is okay with standalone Java programs, where the Java compiler automatically closes the
Resultset for you, but when we deploy this code in a servlet, then we are not guaranteed this
behavior.

For example, take a look at the following code snippet:

public void doGet ( HttpServletRequest req, HttpServletResponse res )


throws ServletException, IOException
{
Connection con = null;
try
{
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
con =
DriverManager.getConnection("jdbc:odbc:issue","super","super");
ResultSet rs = stmt.executeQuery( "SELECT * FROM
person_id_table" );
/* More Code Here */
}
catch( SQLException e )
{
}
finally
{
try
{
if( con != null )
{
con.close(); // Resultset not closed prior to this statement
}
}
catch( SQLException ignored )
{
}
}
}

This code looks perfectly fine. The problem arises when we deploy the code using JSDK1.1
Servlet Engine. It leads to a Windows NT Access Violation Error. The same runs perfectly all right
with ServletExec Servlet Engine. So to be safe, remember to close the ResultSet explicitly before
closing the Connection like in the following code:

public void doGet ( HttpServletRequest req, HttpServletResponse res )


throws ServletException, IOException
{
Connection con = null;
ResultSet rs = null;
try
{
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
con =
DriverManager.getConnection("jdbc:odbc:issue","super","super");
rs = stmt.executeQuery( "SELECT * FROM person_id_table" );
/* More Code Here */
}
catch( SQLException e )
{
}
finally
{
try
{
if( con != null )
{
rs.close();
con.close(); // Resultset closed prior to this statement.
}
}
catch( SQLException ignored )
{
}
}
}

Two Ways to Chain Servlets


In Servlets/JSPs, there are two ways to achieve servlet chaining using
javax.servlet.RequestDispatcher:
1. Include:
2.
3. RequestDispatcher rd = req.getRequestDispatcher("Servlet2");
4. rd.include(req, resp);
5. Forward, where req is HttpServletRequest and resp is HttpServletResponse:
6.
7. RequestDispatcher rd = req.getRequestDispatcher("Servlet3");
8. rd.forward(req, resp);
In JSPs, the above code would look like this:

RequestDispatcher rd = request.getRequestDispatcher("Servlet4");
rd.forward(request, response);
When you use servlet chaining, you delegate the responsibility of generating the response to the
next servlet in the chain.
But, suppose you have some data generated by current servlet that will be required by next
servlet. How would you pass it?
You could keep it in the session, but you would need to remove it from that session after you
fetch it in next servlet—otherwise your session will have useless data once your request is
complete. Not only does this add overhead, but it also makes your next servlet dependent on
session tracking.
You can attach your additional data with the request that you are passing to next servlet:

RequestDispatcher rd = req.getRequestDispatcher("Servlet3");
req.setAttribute("key1", value1);
req.setAttribute("key2", value2);
rd.forward(req, resp);
In the above code, req is HttpServletRequest and resp is HttpServletResponse. The code
attaches two data items, value1 and value2, with the req object. Use the following code to access
this value in the next servlet (Servlet3 in the example):

Object val1 = req.getAttribute("key1");


Object val2 = req.getAttribute("key2");
This attaches two data items (value1 and value2) with the HttpServletRequest object and
forwards them to Servlet3. Servlet3 reads them from the HttpServletRequest and uses them.

Tracking Session Information When Cookie Is Disabled


What is the simplest way to keep track of session information if the cookie is disabled in the
client? Even though we have other alternative solutions like passing the session ID in the query
string or passing the session ID through a hidden variable, the simplest way is to encode the URL
with the session ID. Wherever the URL is used, use the following syntax to encode the URL, then
display or store it. The usage is:

<%= HttpServlet.response.encodeURL("/URL here") %>.


Incase of redirecting the page, the syntax is
<%= HttpServlet.response.encoderedirectURL("/URL here") %>

Now, in your JSP or servlet, you can retrieve the session ID and perform the calculation
respective to the client.

Calling a Servlet From a JSP and Vice-Versa


Servlets and JSPs are the defacto method of server side computing today. Servlets form the logic
of the application code and formatting for output is done with the help of JSPs (Java Server
Pages). Because these two technologies abstract code logic from presentation, communication
between the two has led to rapid code development regarding the true principles of Object
Oriented Programming.

The trick to understanding JSPs is keeping in mind that every JSP is ultimately compiled into a
Servlet. The main thing then becomes understanding the way a servlet communicates with a JSP
and vice-versa. This becomes even more important when sending the output of a calculation in a
servlet to a JSP, or when redirecting a user to a servlet from a JSP.

Calling a JSP from a Servlet, or vice-versa, can be done using the RequestDispatcher interface,
which is part of the Servlet 2.2 specification. Following is the code for sending output to a JSP
page from a servlet:

//Some calculation ; Maybe even a call to EJB(s)


javax.servlet.RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(“/Requested.jsp”);
request.setAttribute(“Name”,”Irfan”);
request.setAttribute(“Language”,”Java”);
dispatcher.forward(request,response);

How to Pass Values Using the 'GET' and 'POST' Methods


Simultaneously
In almost all Web based applications, parameters received from a previous form as a query string
will have to be passed to the next form as the same. However, the form might be receiving some
secure information from the user, which needs to be passed using the 'POST' method, so that it
won't be passed as a querystring. There is a work around enabling one to do both at the same
time.

In a servlets or JSP program, receive the parameters passed as querystring using the following
method:

String value1 = request.getQueryString(“Parameter1”);


// Parameters passed as query string
String value2 = request.getQueryString(“Parameter2”);
// Parameters passes as query string

String Params = “Parameter1=“ + value1 + “&Parameter2=“


+ value2

In JSP, these values must be appended as in the following:

<Form Action=fileName.jsp(can be servlets also)<%=Params%>


Method=“Post”>

In Servlets, these values must be appended as in the following:

PrintWriter out = HttpServletResponse.getWriter();


out.println(“<FORM ACTION= /servlet/deldir” + Params +”
METHOD=POST>“);

This takes care of passing the querystring parameters as they have been received while also
passing the inputs given by the user using the 'POST' Method.

In a servlet or JSP, receive the querystring using “request.getQueryString(“Parameter1”)”.


Receive the values that are passed using 'POST' method as
request.getParameter(“Parameter1”);.

Hopefully this will eliminate hiccups when passing parameters both as querystrings and as form
variables.

Pass Information from a Servlet to a JSP


You can use this kind of bean to pass information from a servlet to a JSP page through a session
variable. For Instance:

DataBean myobj = new dataBean();


myobj.setData(“VALUE1”, value1);
session.setAtribute(“DataBean”,(dataBean)myobj);
Tip: import java.io.Serializable;
import java.util.Properties;
import java.io.*;
import java.util.*;
import java.net.URL;

public class dataBean implements Serializable


{
private Properties data;

public dataBean () {
data = new Properties();
}

public static void main(String args[]) {


System.out.println(“JavaBEAN Start” );
}

public void setData(String name, String value)


{
try {
data.put(name, value);
}
catch (Exception e) {}
}

public String getData(String name) {


String tmp;
try {
tmp = datos.getProperty(name);
}
catch (Exception e) {tmp = ““;}
return tmp;
}
} //END BEAN CLASS

Keep HTML Totally Separate From Java Code


I have been working on Java Servlets and HTML for quite a long time and have always had a
problem keeping HTML code separate from Java code, but now I've found an answer.

While searching on the Net, I found a very good program called XMLC, which really separates
your HTML from Java code. It converts your HTML files into Java classes, then allows you to
manipulate those Java classes using DOM API and regenerates the HTML. It's really cool.

If you are planning to use, or currently using, Java Technology like Servlets or JSP for your next
project, I would advise you to have a look at XMLC.

Related Links: http://www.enhydra.org — For XMLC


http://www.w3.org — DOM

Add Properties To Data Access Objects


How many times have you wished field objects had a "RequiredIfCondition1" or other user-
defined property? You can add one easily:
Set NewProperty = Field1.CreateProperty("FieldNote")
NewProperty.Type = dbText
Field1.Properties.Append NewProperty

Trim the Contents of the Text Box


This tip will trim the contents in the input box of an HTML page using java script. Call the Trim
function by sending the Textbox element as the parameter.

Example:

<form name=frm>
<input name=txtName onBlur="Trim
(document.frm.txtName)">
</form>
<script language=javascript>
function Trim(text)

while(text.value.charAt(0)==' ')
text.value=text.value.substring
(1,text.value.length )
while(text.value.charAt
(text.value.length-1)==' ')
text.value=text.value.substring
(0,text.value.length-1)

}
</script>

Update an HTML Form Using an XML ActiveX Object and a Servlet


The minimum requirement for this tip to work is to have Internet Explorer with MSXML objects
installed when Windows is installed. The DOMDocument is also available in the new versions of
Netscape. This example displays user information based on the login id without submitting the
form.

Create a servlet that will submit an .xml document based on the request parameter "login" value:

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

public class UserInfoServlet


extends HttpServlet {
private static final String CONTENT_TYPE = "text/xml";

//Process the HTTP Get request


public void doGet(HttpServletRequest request, HttpServletResponse
response) throws
ServletException, IOException {
doPost(request, response);
}

//Process the HTTP Post request


public void doPost(HttpServletRequest request, HttpServletResponse
response) throws
ServletException, IOException {
String login = request.getParameter("login");
String info = null;
if (login != null && "guest".equalsIgnoreCase(login)) {
info = "<username>Guest</username>";
}
else {
info = "<username>Unknown</username>";
}
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.println("<?xml version=\"1.0\"?>");
out.println("<output>");
out.println(info);
out.println("</output>");
}
}
Add servlet mapping for this servlet in the web.xml file as follows:

<servlet>
<servlet-name>userinfo</servlet-name>
<servlet-class>UserInfoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>userinfo</servlet-name>
<url-pattern>/ui</url-pattern>
</servlet-mapping>
Following is the HTML page:

<html>
<head><title>User Information</title></head>
<body>
<form name="userinfo">
Enter Login Id:
<input type="text" name="login"
onblur="javascript:doLoadData(this.value)" />
User Information: (Readonly)
<input type="text" name="username" readonly="readonly" />
</form>
</body>

<script language="JavaScript1.4" type="text/javascript">


function doLoadData(login) {
var dd = new ActiveXObject("MSXML.DOMDocument");
dd.async = false;
dd.load('/context/ui?login=' + login);
var node = dd.documentElement.selectSingleNode("/output/username");
document.forms['userinfo'].elements['username'].value = node.text;
}
</script>

</html>
Now, if you type "guest" in the login input, "Guest" or otherwise Unknown will be displayed
automatically.

Perform a Strict Date Validity Check


If you use dates in your program frequently and you want them to be in a particular format, you
don’t get the desired result with VB’s IsDate function. For example, if you want the date to be in
MM/DD/YYYY format, this statement returns True because it assumes the string to be in
DD/MM/YYYY format:
IsDate("23/03/1999") This function checks whether the string passed to it is a valid date in your
chosen format: ' Input Parameters: ' strdate: String containing the Date ' to be validated. '
strDateFormat: The string containing the ' format for the above date. ' OutPut: Boolean Value
indicating whether the ' Date was valid date and in the format ' specified in format string. Public
Function ValidDate(ByVal strDate As _ String, ByVal strDateFormat As String) _ As Boolean Dim
dtCurrDate As Date Dim strModDate As String On Error GoTo DateError ' Convert the Date string
to the Given ' Format strModDate = Format(strDate, strDateFormat) ' strModDate will contain the
formated Date. ' There are three conditions here: ' 1. strDate is invalid Date: strModDate '
contains string same as strDate. ' 2. strDate is valid Date and in Format ' specified: strModDate
will contain string ' same as strDate. ' 3. strDate is valid Date and in not Format ' specified:
strModDate will contain strdate ' converted to the date format specified. ' Below if statement will
Eliminate the 3rd ' condition. If UCase$(strModDate) = _ UCase$(Trim$(strDate)) Then ' Next
statement eliminates 1st ' condition. ' If strdate string is invalid date, ' execution pointer goes to
first ' statement following DateError Label dtCurrDate = Format$(strDate, _ strDateFormat)
ValidDate = IsDate(dtCurrDate) Else ValidDate = False End If Exit Function DateError: ValidDate
= False 'ERROR HANDLING IF DESIRED End Function Executing this function in the Immediate
window yields these results: ?ValidDate("03/03/1999","MM/DD/YYYY") True ?
ValidDate("03/23/1999","MM/DD/YYYY") True ?ValidDate("23/03/1999","MM/DD/YYYY") False

S-ar putea să vă placă și