Java passes all primitive data types by value. This means that a copy is made, so that it cannot be modified. When passing Java objects, you're passing an object reference, which makes it possible to modify the object's member variables. If you want to pass a primitive data type by reference, you need to wrap it in an object.
The easiest of all is to pass it as an array (or even a Vector). Your array only needs to contain a single element, but wrapping it in an array means it can be changed by a function. Here's a simple example of it in action.
public static void increment(int[] array, int amount)
{
array[0] = array[0] + amount;
}
public static void main(String args[])
{
int[] myInt = { 1 };
increment (myInt, 5);
System.out.println ("Array contents : " + myInt[0]);
}
Of course, if you're modifying the contents of parameters passed to a method, you really should try to avoid this behavior. It increases the complexity of code, and really should be avoided. The preferred way is to return a value from a method, rather than modifying parameter values directly.
www.referjava.com
Tuesday, February 13, 2007
How do I debug my Java applets to see what's going wrong?
Often, when an applet behaves strangely or fails to work, the problem is hard to diagnose. Many applets behave fine under Netscape Navigator, only to fail under Internet Explorer (or vice versa). Sometimes a different Java Virtual Machine (JVM) will have less tolerance for a bug, and other times the fault lies in the actual JVM implementation.
The lack of information provided by the browser can be frustrating. However, there is a way to display a debugging console, which will provide developers with additional information. For example, an uncaught exception will generate an exception trace, telling you which method and which exception were involved. Both the later versions of Netscape Communicator and Internet Explorer support these debugging consoles.
To view the Java Console in Netscape Communicator
Load any page with an applet, and then select the following menu option
Communicator -> Tools -> Java Console
www.referjava.com
The lack of information provided by the browser can be frustrating. However, there is a way to display a debugging console, which will provide developers with additional information. For example, an uncaught exception will generate an exception trace, telling you which method and which exception were involved. Both the later versions of Netscape Communicator and Internet Explorer support these debugging consoles.
To view the Java Console in Netscape Communicator
Load any page with an applet, and then select the following menu option
Communicator -> Tools -> Java Console
www.referjava.com
How do I get parameters from a HTML form when using servlets?
When extending javax.servlet.http.HttpServlet, you should override either of the following two methods: -
public void doGet(HttpServletRequest req,
HttpServletResponse res)
public void doPost(HttpServletRequest req,
HttpServletResponse res)
Both of these methods accept as a parameter a HttpServletRequest instance. This allows the servlet to obtain information about the browser request, including the parameters passed to the servlet. By using the String getParameter(String) method, you can request any parameter you need. If the parameter is not present, a null value will be returned.
www.referjava.com
public void doGet(HttpServletRequest req,
HttpServletResponse res)
public void doPost(HttpServletRequest req,
HttpServletResponse res)
Both of these methods accept as a parameter a HttpServletRequest instance. This allows the servlet to obtain information about the browser request, including the parameters passed to the servlet. By using the String getParameter(String) method, you can request any parameter you need. If the parameter is not present, a null value will be returned.
www.referjava.com
How do I gray out components, and prevent users from using them?
Every AWT & Swing component inherits methods that will enable and disable it, from java.awt.Component. The setEnabled(boolean) method allows a component to be disabled, and later enabled. Previously, AWT components could be enabled and disabled by calling their enable() and disable() methods. However, these methods have been deprecated, and should no longer been used.
// Disable button (b)
b.setEnabled ( false );
// Enable button (b)
b.setEnabled ( true );
www.referjava.com
// Disable button (b)
b.setEnabled ( false );
// Enable button (b)
b.setEnabled ( true );
www.referjava.com
How do I make cookies expire after a set time period? For example, in five minutes time for security reasons
Depending on how you use the data stored in a cookie, it is often a good idea to make the cookie expire. Since anyone using the browser will have the cookie sent on their behalf, it may appear to be a legitimate user when in actual fact it is not. This often happens in places like Internet cafes, school or university computing labs, or libraries. If your cookie sends a user identifier that facilitates access to sensitive data, or allows changes to be made (for example, a web-based email service), then you should expire cookies after a small time period. If the user keeps using your servlet, you always have the option of resending the cookie with a longer duration.
To specify an expiration time, you can use the setMaxTime(int) method of javax.servlet.http.Cookie. It takes as a parameter the number of seconds before the cookie will expire. For example, for a five minute expiration, we would do the following :-
// Create a new cookie for userID from a fictitious
// method called getUserID
Cookie cookie = new Cookie ("userID", getUserID());
// Expire the cookie in five minutes (5 * 60)
cookie.setMaxTime( 300 );
When the cookie is sent back to the browser, using HttpServletResponse.addCookie(Cookie), it will only be returned by the browser until the expiration date occurs. If you'd prefer, you can also specify a negative value for setMaxTime(int), and the cookie will expire as soon as the browser exits. Note however that not everyone will shutdown their browser, and it might be available for minutes, hours even days. Finally, specifying a value of zero will expire the cookie instantly.
www.referjava.com
To specify an expiration time, you can use the setMaxTime(int) method of javax.servlet.http.Cookie. It takes as a parameter the number of seconds before the cookie will expire. For example, for a five minute expiration, we would do the following :-
// Create a new cookie for userID from a fictitious
// method called getUserID
Cookie cookie = new Cookie ("userID", getUserID());
// Expire the cookie in five minutes (5 * 60)
cookie.setMaxTime( 300 );
When the cookie is sent back to the browser, using HttpServletResponse.addCookie(Cookie), it will only be returned by the browser until the expiration date occurs. If you'd prefer, you can also specify a negative value for setMaxTime(int), and the cookie will expire as soon as the browser exits. Note however that not everyone will shutdown their browser, and it might be available for minutes, hours even days. Finally, specifying a value of zero will expire the cookie instantly.
www.referjava.com
How do I read browser cookies from a servlet?
Reading cookies from a servlet is quite 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, Cookies[] getCookies() which returns an array of Cookie objects. However, if no cookies are available, this value may be null, so be sure to check before accessing any array elements.
// Check for cookies
Cookie[] cookie_jar = request.getCookies();
// Check to see if any cookies exists
if (cookie_jar != null)
{
for (int i =0; i< cookies.length; i++)
{
Cookie aCookie = cookie_jar[i];
pout.println ("Name : " + aCookie.getName());
pout.println ("Value: " + aCookie.getValue());
}
}
www.referjava.com
// Check for cookies
Cookie[] cookie_jar = request.getCookies();
// Check to see if any cookies exists
if (cookie_jar != null)
{
for (int i =0; i< cookies.length; i++)
{
Cookie aCookie = cookie_jar[i];
pout.println ("Name : " + aCookie.getName());
pout.println ("Value: " + aCookie.getValue());
}
}
www.referjava.com
How do I send cookies from a servlet?
HTTP is a stateless protocol, which makes tracking user actions difficult. One solution is to use a cookie, which is a small piece of data sent by a web browser every time it requests a page from a particular site. Servlets, and CGI scripts, can send cookies when a HTTP request is made - though as always, there is no guarantee the browser will accept it.
Cookies are represented by the javax.servlet.http.Cookie class. Cookie has a single constructor, which takes two strings (a key and a value).
// Create a new cookie
Cookie cookie = new Cookie ("counter", "1");
Adding a cookie to a browser is easy. Cookies are sent as part of a HTTPServletResponse, using the addCookie( Cookie ) method. You can call this method multiple times, but remember that most browsers impose a limit of ten cookies, and 4096 bytes of data per hostname.
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws IOException
{
response.addCookie(new Cookie("cookie_name", "cookie_value"));
}
www.referjava.com
Cookies are represented by the javax.servlet.http.Cookie class. Cookie has a single constructor, which takes two strings (a key and a value).
// Create a new cookie
Cookie cookie = new Cookie ("counter", "1");
Adding a cookie to a browser is easy. Cookies are sent as part of a HTTPServletResponse, using the addCookie( Cookie ) method. You can call this method multiple times, but remember that most browsers impose a limit of ten cookies, and 4096 bytes of data per hostname.
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws IOException
{
response.addCookie(new Cookie("cookie_name", "cookie_value"));
}
www.referjava.com
Subscribe to:
Posts (Atom)