Documente Academic
Documente Profesional
Documente Cultură
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.
Now, the implementations can just extend these adapters instead of implementing the EntityBean
and SessionBean interfaces directly. Like:
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!
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:
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.
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.
1 - The order of iteration for elements in a Hashtable will be unpredictable, and will generally
differ from one program invocation to the next.
applet_test.java: This is the sample Java applet that returns the hostname of the machine and the
IP address associated with that hostname.
<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.
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.*;
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();
}
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.
Field f = c.getField(requestParam);
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.
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.
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.
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).
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:
..
.. 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.
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.
Servlet Code:
gz.write(data.getBytes());
gz.close();
out.close();
}
catch(Exception e)
{
System.out.println("In CompressServlet: Exception in doGet");
}
}
//Applet Code:
try
{
GZIPInputStream gz = new GZIPInputStream( getData() );
gz.close();
}
catch (IOException e)
{
System.out.println("In UncompressApplet: Exception in readData()");
}
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 :
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:
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):
Now, in your JSP or servlet, you can retrieve the session ID and perform the calculation
respective to the client.
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:
In a servlets or JSP program, receive the parameters passed as querystring using the following
method:
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.
Hopefully this will eliminate hiccups when passing parameters both as querystrings and as form
variables.
public dataBean () {
data = new Properties();
}
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.
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>
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.*;
<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>
</html>
Now, if you type "guest" in the login input, "Guest" or otherwise Unknown will be displayed
automatically.