Tuesday, September 11, 2007

Java FAQ's

1. Can there be an abstract class with no abstract methods in it?
- Yes

2. Can an Interface be final?
- No

3. Can an Interface have an inner class?
- Yes.

public interface abc
static int i=0; void dd();
class a1
int j;
public static void main(String a1[])
System.out.println("in interfia");

4. Can we define private and protected modifiers for variables in interfaces?
- No

5. What is Externalizable? -
Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)

6. What modifiers are allowed for methods in an Interface?
- Only public and abstract modifiers are allowed for methods in interfaces.

7. What is a local, member and a class variable?
- Variables declared within a method are “local” variables. Variables declared within the class i.e not within any methods are “member” variables (global variables). Variables declared within the class i.e not within any methods and are defined as “static” are class variables

8. What are the different identifier states of a Thread?
- The different identifiers of a Thread are: R - Running or runnable thread, S - Suspended thread, CW - Thread waiting on a condition variable, MW - Thread waiting on a monitor lock, MS - Thread suspended waiting on a monitor lock

9. What are some alternatives to inheritance?
- Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn’t force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).

10. Why isn’t there operator overloading?
- Because C++ has proven by example that operator overloading makes code almost impossible to maintain. In fact there very nearly wasn’t even method overloading in Java, but it was thought that this was too useful for some very basic methods like print(). Note that some of the classes like DataOutputStream have unoverloaded methods like writeInt() and writeByte().

11. What does it mean that a method or field is “static”?
- Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class. Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That’s how library methods like System.out.println() work. out is a static field in the java.lang.System class.

12. How do I convert a numeric IP address like into a hostname like java.sun.com?

String hostname = InetAddress.getByName("").getHostName();

13. Difference between JRE/JVM/JDK?

14. Why do threads block on I/O?
- Threads block on i/o (that is enters the waiting state) so that other threads may execute while the I/O operation is performed.

15. What is synchronization and why is it important?
- With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often leads to significant errors.

16. Is null a keyword?
- The null value is not a keyword.

17. Which characters may be used as the second character of an identifier,but not as the first character of an identifier?
- The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.

18. What modifiers may be used with an inner class that is a member of an outer class?
- A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.

19. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
- Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.

20. What are wrapped classes?
- Wrapped classes are classes that allow primitive types to be accessed as objects.

21. What restrictions are placed on the location of a package statement within a source code file?
- A package statement must appear as the first line in a source code file (excluding blank lines and comments).

22. What is the difference between preemptive scheduling and time slicing?
- Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

23. What is a native method?
- A native method is a method that is implemented in a language other than Java.

24. What are order of precedence and associativity, and how are they used?
- Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left

25. What is the catch or declare rule for method declarations?
- If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.

26. Can an anonymous class be declared as implementing an interface and extending a class?
- An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

27. What is the range of the char type?
- The range of the char type is 0 to 2^16 - 1.

Thursday, September 6, 2007

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++)
bcookiefound = true;
//desired cookie found, use it
if(bcookiefound == false)
//cookie not found.

Look Up a Bean Interface in EJB 3.0

In principle, in EJB 3.0, you can access a bean from another bean by looking it up in the interface (local or remote). Here are two solutions for doing that:

1. Through the JNDI, you still have the portability:

//get the default JNDI initial context
Context ctx=new InitialContext();
//get the bussiness interface
Object obj=ctx.lookup(BusinessInterface.class.getName());
//convert obj
BusinessInterface bi=(BusinessInterface)obj;

2. Through the @EJB annotiation:

@EJB BusinessInterface bi; //cooool !

Spring 2.1 Grows New Features and Evolutionary Enhancements

In this article, I will look at the latest and upcoming releases of the Spring Java framework. In one of my previous articles, "Spring: the Eclectic Framework," I discussed the Spring application framework. But since then, Interface21, the company responsible for development and support of the framework, implemented many new features and has released version 2.0 of Spring. The upcoming preview edition 2.1 is already underway, and I will discuss what has changed and improved in this new version over the previous one. Because the Spring framework is an aggregation of various components and modules, its parts have evolved differently, but overall version 2.1 is a major improvement over version 1.x and a sizable improvement over 2.0.

It's good to see that these changes are evolutionary, rather then revolutionary, and are inline with the development trends in the Java community. Among the new enhancements are: support for the Java SE 6 features, integration with JSF, enhancements in the Aspect Oriented Programming (AOP) framework, greater Java Annotations support, more configuration, and bean wiring options (now with Java annotations in addition to XML), as well as a refinement of module for web flow management called Web Flow 1.1. Additionally, Spring 2.1 introduces Portlet MVC framework, integration with Java Persistence API (JPA), and the ability for Spring beans to be implemented in dynamic languages, such as Groovy, JRuby, and Beanshell. There are also further improvements to the core components of Spring—IoC container and Dependency Injection mechanism.
Java Annotations and Spring

Since Java version 1, there were always ways to define specific language behavior using tag metadata. As of Java 5, developers can create custom metadata tags and put them in the code to achieve certain behavior. These custom tags are called annotations. For example, there are three metadata types that are predefined by the Java language specification itself: @Deprecated, @Override, and @SuppressWarnings. An annotation is a special kind of modifier, and can be implemented in situations where other modifiers, such as public, static, or final are used. Annotations can be declared with no value or one or more parameters.

For example, a new annotation can be declared like this:

public @interface Copyright {}

or like this

public @interface Copyright { int yr(); }

and then used with in source code like this:

@Copyright public class Vlad { ... }


@Copyright(2007) public class Vlad { ... }

The definition of annotations is similar to the Java Interface definition, but each method declaration defines an element of the annotation type. Method declarations must not have any parameters or a throws clause. In addition, all return types are restricted to primitives, String, Class, enums, annotations, or arrays of these types.

By definition, annotations have no direct effect on the operation of the code they annotate. So what good do they do? Their usefulness is in their ability to affect the semantics of the running program. This means that they are commands to the compiler (or other tools and libraries) to do something special with the code. For example, the default annotation @SuppressWarnings tells the Jave compiler to ignore and not show any warnings generated by the code annotated by this tag. Similarly, the @deprecated tag indicates that the method marked with it will not be supported in the future, and the compiler needs to generate an appropriate message to the developer.

Spring had some annotations in its early version, but added many more in version 2.0 and even more in version 2.1. Version 1.2 introduced the @Transactional and @ManagedResource tags (for JMX management). Also, the new version adds tags such as, @Configurable, @Required, and @Repository, among others. New annotations within Spring's Aspect Oriented Programming (AOP) are also used to express pointcuts and advices.

I have barely scratched the surface of the annotations because the purpose of this article is to provide an overview. However, if you are interested in gaining more detailed understanding of annotations, I suggest looking at the AspectJ 5 language.
Spring Configuration

The current process of configuring the Spring components is largely done with the XML configuration files. Without proper tools, novice developers may face a steep learning curve when challenged with the task of Spring component configuration and bean "wiring" for the IoC processes. Luckily, more IDEs are coming out to help with configuration task and I will talk about some of them later in this article.

The upcoming 2.1 release will introduce more ways to configure Spring components through annotations in the source code. What this means is that, in addition to the old way of configuring Spring with plain XML, developers will be able to annotate their classes (or beans) with special tags to achieve the same effect. It also will be necessary for the tools' vendors to implement support for this feature so that developers can get the full benefit.
The Spring Web Flow 1.1 Module

Even though Spring is considered a Java web framework, there is really not much in core Spring that would help web developers create web applications. Most of the Spring modules deal with simplification of non-visual aspects or back-end processes of Java programming, such as Inversion of Control, Aspect Oriented Programming, JDBC connections, exception handling, and so forth.

Therefore, it is not surprising that the developers of Spring introduced a separate module dealing primarily with web application flow management. This module is called Spring Web Flow, and is designed to be a framework for web application navigation (not to be confused with MVC). Spring Web Flow is similar in functionality to any modern web framework, such as Struts or Web Work, but different in its packaging. In fact, Spring Web Flow can be integrated with Struts and Java Server Faces (JSF). And, version 1.1 of Web Flow actually has specific features for tighter integration with JSF.

With Web Flow, developers can "set" or create a series of steps based on use-cases, and tie them in easily with the other Spring modules on the back end, or with JSF on the front -end. The flows can be separated into reusable modules, chained as sub-flows, tested in isolation, and deployed to different target containers (such as Servlet or Portlet containers).

Here is an example of a Spring flow:

Figure 1: Spring Web flow diagram

Flows are described using XML, and once created, do not need to be changed when the environment executing them changes. For example, same flow definition should work in the Servlet container and with JUnit, Spring MVC, or Struts. Because flows are configuration based, the Spring IDE includes support for editing and visualizing them graphically. (See more about IDE support later in the article.)

Additionally, here are some more features of the Spring Web Flow module:

* Automatic garbage collection of memory allocated during flow execution
* Changes to navigation rules do not require container restart
* Automatic browser button support (back, forward, refresh)

Both Spring and Spring Web Flow are released under the Apache license.

Spring IDE Tools

The Spring framework has gained enough momentum in the enterprise developer market that heavy-weight IDE vendors are starting to take notice and incorporate support for Spring into their products. This, in turn, can serve as a snowball effect and introduce Spring to more developers. Oracle Corporation has recently released an extension to its flagship JDeveloper IDE that will incorporate a Spring framework-based SDK, and include support for Spring 1.x and 2.0. The Oracle IDE will help developers by providing auto-complete, code insight, and XML validation of Spring definitions.

Figure 2: Oracle JDeveloper 10g screen shot

The folks who developed the original Spring IDE also just released the final version of Spring IDE 2.0. The Spring IDE is a plug-in for the Eclipse IDE and Eclipse 3.2.x (or newer) is required to run Spring IDE 2.0. The new IDE is a huge improvement over version 1.x. It adds support for Spring 2.0, Spring Web Flow, Spring AOP and Spring JavaConfig and, according to its web site—Spring IDE 2.0 also eliminates approximately 250 bugs.

Figure 3: Spring IDE Screen Shot

Because in the past the only IDE available was the Spring IDE 1.x (which seems to have been very buggy according to its own web site), developers who did not want to write tons of Spring configuration XML code by hand, or deal with remembering and typing overly long Spring class names, tried not to use the technology if they did not have to. The enterprise tool support is very good news for the Spring framework and the developers using it. The development of the solid IDEs for the Spring framework, such as JDeveloper and substantial improvement in original Spring IDE, means that working with the framework will be much easier and the learning curve may decrease.

In this article, I discussed new features of the Spring framework 2.0 and 2.1, such as annotations, web flow, and so on. I also mentioned new IDE vendor support for Spring. It will be interesting to see what other IDEs with jump onboard with Spring support, what new features will grow in the Spring framework, and whether the adoption of Spring increases.

* Java Annotations: http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html
* Spring 2.0: What's New and Why it Matters: http://www.infoq.com/articles/spring-2-intro
* Interface21: Springframework.org
* SpringIDE: http://springide.org/project/wiki/TOC

Wednesday, September 5, 2007

Read and write data with Java's I/O streams

All of Java's I/O is based upon streams. Once you learn the syntax for one stream; you can work with any other type in Java. This article introduces some ways of working with Java streams.

The Java input/output (I/O) facilities provide a simple, standardised API for reading and writing character and byte data from various data sources. In this article, we'll explore the I/O classes, interfaces, and operations provided by the Java platform. Let's start by taking a look at Java streams.


All of Java's I/O facilities are based on streams that represent flowing sequences of characters or bytes. Java's I/O streams provide standardised ways to read and write data. Any object representing a mutable data source in Java exposes methods for reading and writing its data as a stream.

Java.io is the main package for most stream-oriented I/O classes. This package presents two abstract classes, InputStream and OutputStream. All other stream-oriented I/O classes extend these base classes.

The java.io package exposes a number of classes and interfaces that provide useful abstractions on top of the character and byte reading and writing operations defined by InputStream and OutputStream. For example, the ObjectInputStream class provides methods that allow you to read data from a stream as a Java object, and the ObjectOutputStream provides methods that allow you to write data to a stream as a Java object.

Optimised reading and writing

JDK 1.1 added a collection of reader and writer classes that provide more useful abstractions and improved I/O performance than the existing streams classes. For instance, the BufferedReader and BufferedWriter classes are provided to read text from and write text to character-based input streams and output streams. The BufferedReader class buffers characters to more efficiently read characters, arrays, and lines. The BufferedWriter class buffers characters to more efficiently write characters, arrays, and strings. The size of the buffer used by the BufferedReader and BufferedWriter classes can be set as desired.

Reader and writer classes provided by the Java I/O Framework include the LineNumberReader class, the CharArrayReader class, the FileReader class, the FilterReader class, the PushbackReader class, the PipedReader class, and the StringReader class, among others. These classes are wrappers on top of the InputStream and OutputStream classes and thus provide methods that are similar to InputStream and OutputStream. However, these classes provide more efficient and useful abstractions for reading and writing specific objects, such as files, character arrays, and strings.

Reading data

An input stream is typically opened for you automatically when it is retrieved from the corresponding data source object or when you construct one of the reader objects. For example, to open the input stream for a file, we pass the name of the file into a java.io.FileReader object's constructor as follows:

java.io.FileReader fileReader = new java.io.FileReader("/home/me/myfile.txt");

To read the next available byte of data from a FileReader's underlying input stream, use the read method with no parameters. The snippet in Listing A reads text from a file, one character at a time, and writes it to System.out.

Listing A

int aChar = 0;
while ((aChar = fileReader.read()) >= 0)

To read a given number of bytes from an input stream into a char array, use the read method with one char[] parameter. The length of the array is used to determine the number of characters to read. Listing B demonstrates this technique.

Listing B

char[] buffer = new char[256];
while ((fileReader.read(buffer)) >= 0)
System.out.print(new String(buffer));

To close an input stream and release any system resources used by the stream, use the close method as follows:


Writing data

Like an input stream, an output stream is typically opened for you automatically when it is retrieved from the corresponding data source object or when you construct one of the writer objects. For example, to open the output stream for a file, we pass the name of the file into a java.io.FileWriter object's constructor as follows:

java.io.FileWriter fileWriter = new java.io.FileWriter("/home/me/out.txt");

To write one specified character to an output stream, use the write method with one int parameter. The int parameter represents the character to write.

int aChar = (int)'X';


To write a specific number of bytes from a specified char array starting at a given offset to an output stream, use the write method with a char[] parameter, an int offset parameter, and an int length parameter as shown in the following example:

fileWriter.write(buffer, 0, byteCount);

To close an output stream and release any system resources associated with the stream, use the close method, like this:


To force any buffered data out of an output stream, use the flush method as follows:


Putting it all together

We can use what we have learned to read from one file and simultaneously write to another, as demonstrated in Listing C.

Listing C

java.io.FileReader fileReader =
new java.io.FileReader("/home/me/temp.txt");
java.io.FileWriter fileWriter =
new java.io.FileWriter("/home/me/out.txt");
char[] buffer = new char[256];
int byteCount = 0;
while ((byteCount = fileReader.read(buffer)) >= 0)
fileWriter.write(buffer, 0, byteCount);
catch(Exception e)


The Java I/O facilities add a simple and standardised API for reading and writing character and byte data from various data sources. Experience obtained while working with Java streams for one type of data source can be carried over to any other type of data source exposed by Java.

Tuesday, September 4, 2007

Determine the available memory in Java

Java Memory Allocation
The following example shows how much memory that JVM has allocated for your application:

Runtime runtime = Runtime.getRuntime();
System.out.println("allocated memory: " + runtime.totalMemory() / 1024);

The totalMemory() method returns the amount of memory the JVM has allocated from the operating system. Unless you specified the amount of memory to allocate using the -Xms command line option, the totalMemory() method will continually fluctuate as objects are allocated and the garbage collection cleans them up.

The following example shows how to discover how much memory is being used by your application:

Runtime runtime = Runtime.getRuntime();
System.out.println("free memory: " + runtime.freeMemory() / 1024);

The freeMemory() method will return the amount of free memory from the allocated memory. Since this value does not include any memory that hasn't yet been allocated by the JVM, you will need to get a complete picture of the free memory that your application would be able to use. To do this, you need to include the amount of memory that hasn't yet bee allocated by the JVM, but could be allocated if necessary. The following example shows how:

Runtime runtime = Runtime.getRuntime();
long maxMemory = runtime.maxMemory();
long allocatedMemory = runtime.totalMemory();
long freeMemory = runtime.freeMemory();
System.out.println("free memory: " + freeMemory / 1024);
System.out.println("allocated memory: " + allocatedMemory / 1024);
System.out.println("max memory: " + maxMemory / 1024);
System.out.println("total free memory: " + (freeMemory + (maxMemory - allocatedMemory)) / 1024);

Sample results from the test below show that Java only allocated a small amount of memory and a large amount of memory is still available to the application:

free memory: 294
total memory: 1984
max memory: 65088
total free memory: 63398


Java has several design patterns Singleton Pattern being the most commonly used design pattern. Java Singleton pattern belongs to the family of design patterns, that govern the instantiation process. This design pattern proposes that at any time there can only be one instance of a singleton (object) created by the JVM.

The Singleton class’s default constructor is made private, which prevents the direct instantiation of the object by others (Other Classes). A static modifier is applied to the instance method that returns the singleton object as it then makes this method a class level method that can be accessed without creating an object.

One such scenario where it might prove useful is when we develop the Java Help Module in a project. Java Help is an extensible, platform-independent help system that enables authors and developers to incorporate online help into applications. Since at any time we can do only with one main Help object and use the same object in different screens, Singleton Pattern suits best for its implementation.

A singleton pattern can also be used to create a Connection Pool. If programmers create a new connection object in every java class that requires it, then its clear waste of resources. In this scenario by using a singleton connection class we can maintain a single connection object which can be used throughout the Java application.

Implementing the Singleton Pattern

To implement this design pattern we need to consider the following 4 steps:

Step 1: Provide a default Private constructor

public class SingletonObjectDemo
//Note that the constructor is private
private SingletonObjectDemo ()
// Optional Code

Step 2: Create a Method for getting the reference to the Singleton Object

public class SingletonObjectDemo{
private static SingletonObject singletonObject;

//Note that the constructor is private
private SingletonObjectDemo (){
// Optional Code

public static SingletonObjectDemo getSingletonObject(){
if (singletonObject == null){
singletonObject = new SingletonObjectDemo ();
return singletonObject;



We write a public static getter or access method to get the instance of the Singleton Object at runtime. First time the object is created inside this method as it is null. Subsequent calls to this method returns the same object created as the object is globally declared (private) and the hence the same referenced object is returned.

Step 3: Make the Access method Synchronized to prevent Thread Problems.

public static synchronized SingletonObjectDemo getSingletonObject()

It could happen that the access method may be called twice from 2 different classes at the same time and hence more than one singleton object being created. This could violate singleton pattern principle. In order to prevent the simultaneous invocation of the getter method by 2 threads or classes simultaneously we add the synchronized keyword to the method declaration

Step 4: Override the Object clone method to prevent cloning.

We can still be able to create a copy of the Object by cloning it using the Object’s clone method. This can be done as shown below

SingletonObjectDemo clonedObject = (SingletonObjectDemo) obj.clone();

This again violates the Singleton Design Pattern's objective. So to deal with this we need to override the Object’s clone method which throws a CloneNotSupportedException exception.

public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();

The below program shows the final Implementation of Singleton Design Pattern in java, by using all the 4 steps mentioned above.

class SingletonClass{

private static SingletonClass singletonObject;

/** A private Constructor prevents any other class from instantiating. */
private SingletonClass(){
// Optional Code

public static synchronized SingletonClass getSingletonObject()
if (singletonObject == null){
singletonObject = new SingletonClass();
return singletonObject;

public Object clone()throws CloneNotSupportedException
throw new CloneNotSupportedException();


public class SingletonObjectDemo{
public static void main(String args[]){
// SingletonClass obj = new SingletonClass(); Compilation error not allowed

//create the Singleton Object..
SingletonClass obj = SingletonClass.getSingletonObject();

// Your Business Logic
System.out.println("Singleton object obtained");


Another approach to using Singleton pattern

We don't need to do a lazy initialization of the instance object or to check for null in the get method. We can also make the singleton class final to avoid sub classing of singletons that may cause other problems.

public class SingletonClass {
private static SingletonClass ourInstance = new SingletonClass();
public static SingletonClass getInstance() {
return singletonObj; }
private SingletonClass() {

In Summary, the job of the Singleton class is to enforce the existence of a maximum of one object of the same type at any given time. Depending on your implementation, your Singleton class and all of its data might be garbage collected. Hence we must ensure that at any point there must be a live reference to the Singleton class when the application is running.

Saturday, September 1, 2007

Open Source JSP Tag Library provides Java Front-End to GoogleMaps API

Google:maps - a freeware, open-source project to provide a 100% Java front-end to the GoogleMaps API - is a JSP taglibrary that provides cross-browser and clean GoogleMaps output, every time, according to the enthusiasts behind the project.

Led by Tom E. Cole, whose day job is as general manager of Lamatek, Inc., the group says that the Tag Library provides JSP developers with the ability to create fully functional Google Maps with absolutely no JavaScript or AJAX programming.

"I like JSP technology," Cole explains, "and I like GoogleMaps. To me it was a perfect match, creating an industry standard front-end to a leading edge technology, making it available to many developers without the burden of learning a whole new API or to many even a whole new programming language."

"It goes beyond the standard API by providing complete 100% Java event handling, either synchronously or asynchronously, includes advanced overlays like circles, polygons, boxes and the ability to hook the mousewheel into the zoom function," notes Cole.

He adds: "The taglibrary has been fully tested on all IE, Firefox, Netscape and Opera browsers supported by GoogleMaps to ensure consistent, cross-browser functionality. Using the Google Maps JSP Taglibrary you'll never see that 'it works in Firefox, but not IE' problem ever again."

Cole is quick to offer full credit two fellow developers: "Joaquin Cuenca Abela was kind enough to offer the Javascript code that maps the mousewheel to the zoom function; Kapil at tripmojo.com provided the Javascript function for drawing circles."

Developers can incorporate Google Maps JSP Taglibrary with JSTL and its own built in event handling capabilities to create fully interactive 2-way mapping applications, Cole explains.


Friday, August 31, 2007

Ten Aspects of Security to Improve Application Strength

When designing and developing applications, there are a lot of pieces to juggle at the outset, and when the complexities, priorities, and pressures of business are combined, quality application development easily can become something of an unreachable goal. As a final ingredient, the need for security in the application can further darken an already ominous undertaking. The situation is not hopeless, however, and both quality and security can be achieved by approaching applications logically and with a few guidelines driven from experience. This article provides a set of important pieces that can help application developers avoid critical mistakes as they relate to security within applications.

The first part discusses areas of security that relate to all applications where some of the most common mistakes are made:

1. Design time
2. Layers
3. Think like the enemy

The second part focuses on the application of security within the application where more technical weaknesses can be uncovered:

1. Authentication
2. Access control
3. Confidentiality/privacy
4. Encryption
5. Segregation of data and privileges
6. Error handling
7. Testing for security

Design Time

One of the largest mistakes application designers can make is to think of security as a bolt-on feature that always can be added at some later point, or upon request. Security affects all aspects of an application and needs to be looked at and considered from all angles, dimensions, and in all areas during design and development. Start thinking about security early when working on the initial ideas for an application. Consider the following questions:

1. What kind of data will the application be using and are there requirements for security such as authentication, access control, privacy, networking, and storage?
2. What kind of security-specific technologies and components will be needed? Look at the larger picture and where the application fits, including interoperability and standards such as Role Based Access Control, Public Key Cryptography, and SSL/TLS.
3. Are there any laws, regulations, and rules that govern the application, how it's used, or how data is handled? These often mandate auditing and logging, transactional components, and reporting.

Security needs to be woven into the application at all stages. To assure that this happens, some basic steps can be followed during the requirements gathering stage of application design:

1. Create a section dedicated to security in functional and design documents
2. Start with a list of questions and issues that relate to security. For example: "Do we need authentication here?" "What kind of users are expected to use this application?" "How do we want to handle bad input in module X?" "What effect does my application have on other systems and applications with which it interacts?"
3. As the functional requirements unfold, many of the questions can be answered. Repeat this cycle for the design phase.


Security should be thought of in layers. It is very easy to fall into the trap of perimeter-based security—only at the borders, such as the network via a firewall. The network is only one layer where security needs to be present. Any areas of interaction with external applications, users, and systems should also have security designed into them, as should the data handling inside an application.

A truly comprehensive model can be created by applying security to many layers of an application. Here is a model that roughly follows the well-known OSI layers for networking:

1. Physical Layer: Consider how controlling physical access to the system can add to or detract from the security of the application.
2. Network: Consider the interaction with the network that an application has, including the systems it interacts with, how network access is protected, and where.
3. Borders: The edges of the application, including its points of interaction with other applications, APIs, and libraries.
4. Presentation: The user interface of the application, such as a command line, a GUI, or Web browser.
5. Internal: The internals of the application, where data is consumed, rules are set, exceptions made, and memory manipulated.

Although these layers present a guideline, it is important to consider each application in its appropriate context by identifying the layers that reflect the application and its usage. Some applications will have more, or less, layers, and may differ from one application to the next.
Think Like The Enemy

When arriving at functionality and the corresponding design for an application, the most common mistake is to consider only ideal-world functionality. This is the act of defining functionality of an application exclusively by the best-case scenario of what you want users to do. Invariably, people will make mistakes and do things with an application that it was never meant to do—if the constraints of an application are not defined and handled, the effect can be severe. Other people will attempt to find vulnerabilities in any application by doing exactly that which one would not want them to do. Therefore, one can more easily be proactive during the design phase of an application by pondering the kinds of behavior and actions that are not desired and to implement functionality to prevent them from happening. Each of the aforementioned layers of an application will have well-known types of attacks that can be avoided and protected against.

It is also important to understand the risks surrounding an application. The best way to analyze risk is to put the application in context with its intended use—its relationship to other high- or low-risk applications and systems, and the data that it uses. Does the nature of the application, such as an e-commerce application, naturally make it a more appealing target, due to the plethora of important and sensitive information with which it works? Is the application known to interact with other systems, on which sensitive or critical material is located? Does the application itself constitute a critical piece of an organization's lifeblood? All of these aspects should be considered when evaluating the security of an application. If the application increases an organization's risk with its use, the appropriate attention needs to be given to the security in the application.

When creating applications that have some form of user interaction, multiple system interaction, or any dealing with foreign components, it is probable that some form of authentication be used to protect the application. The most prevalent mistakes with authentication are to:

1. Have no authentication.
2. Define static and hard-coded authentication information.
3. Negate the effectiveness of having authentication with poor authentication management.

For example, the most commonly used authentication mechanism is the username and password. Although not the strongest form of authentication, it can be used safely to provide an adequate level of security, depending upon the context. There are, however, several ways to render username and password authentication very insecure:

1. Perform authentication in cleartext over the network.
2. Store the password in plaintext in a file or database.
3. Hard-code credentials into the application.
4. Create pre-defined/static special accounts.

Some ways to increase security for username/password authentication:

1. Utilize encryption for network-based authentication, such as SSL/TLS.
2. When storing passwords, store password hashes if there is no need to recover the plaintext of the original password. If recovery of the original password is desired, use encryption to securely store it (see the following section on encryption).
3. Mandate the use of longer passwords and a mixture of characters, including mixed-case alpha-numeric and special characters.

Access Control

The biggest mistake that an application designer can make is to ignore access control as a piece of required functionality. It is rare that every user or system that interacts with an application should have the same rights across that application. Some users may need access to particular pieces of data and not others; some systems should or should not be able to access the application. Access to specific components, functions, or modules within an application should also be controlled. Access control also is important for auditing and regulatory compliance. Some common ways of managing access control are:

1. Read, write and execute privileges: A file
2. Role-based access control: administrators, users
3. Host based access IP address, machine name
4. Object-level access control code object, multiple reader/single writer


Many applications use, manipulate, and consume sensitive data. The mistake often made here is to treat all data the same and fail to recognize the sensitive nature of some data types. Common examples of sensitive data includes:

1. Personal information about users: Includes names, addresses, phone numbers, ID numbers; Social Security, passport, and license numbers
2. Security information: Includes keys, passwords, tokens
3. Configuration information for the application
4. Financial information (e-commerce related): credit card and account numbers

Sensitive data can be segregated from other data within the application (see below), and the methods used to manipulate the data can be access controlled (above). When developing applications, especially in this day of increasing regulations and rules, it is even more important to research any regulations or procedures that may govern the application or its use. This is especially common in the financial, healthcare, energy, and other critical infrastructures.


As with most security technologies, it is easy to render the security strength ineffective if used improperly. Encryption is an important component in most security architectures, but there are some complexities involved with its use. The following pieces need to be considered when using encryption:

1. The type of algorithm: symmetric or asymmetric
2. The generation of keys and keying material
3. The management of keys and keying material
4. The application's performance requirements

There are two types of encryption algorithms: asymmetric and symmetric. Asymmetric algorithms have separate keys for encryption and decryption, use longer key lengths, have slower performance, and have easier key distribution with somewhat difficult key management. Symmetric algorithms use a single key for encryption and decryption, typically have smaller key lengths, higher performance, and more complex key distribution with simpler key management. Choosing a type and algorithm is often done automatically depending on the technologies used. Unless implementing a new or proprietary protocol, the use of encryption is generally governed by an existing standard.

When using encryption, there are several pieces of information that affect its strength. This includes how the keys are generated and the sources of data used to start key generation. Initialization vectors used to seed keying material or encryption operations often rely on sources of randomness and entropy. What these sources are and how truly random they are can result in weaker keys and encryption that allows attackers to compromise the data. Often, the most reliable sources of randomness are hardware and many systems have built-in pseudo-random number generators (PRNG).

Once keys are generated, the next challenge is their management, which includes storage, distribution, revocation, and updates. The problem of key storage is fairly obvious, with the plethora of smart cards, USB tokens, and dongles readily available. Because the key used for decryption must be stored safely, the use of encryption can become useless if private keys are stored on globally accessible media, such as on a hard drive. The fun does not stop there, however. For symmetric encryption, where a single key is used for both encryption and decryption, that key must somehow be communicated to the parties that want to encrypt data. It is obviously not ideal to simply transmit the key via some common way (e-mail, a file, Instant Messaging, and so forth), because it can be compromised easily. For this reason, several schemes are used to exchange keys, including Diffie-Hellman key exchange, the use of Public Key cryptography to exchange keys, and other algorithms that allow for mutual calculation of keys. Finally, the management of keys can become tricky, especially for keys that are compromised or expire when used on data that persists for long periods of time. If keys are lost, stolen, or expired, new keys must be generated and the data that may have been encrypted with the old keys must then be decrypted and re-encrypted using the new keys.

Finally, the performance requirements of the application can affect which encryption technologies are used. Public key algorithms are computationally expensive and will result in dramatic decreases in performance and throughput. Symmetric ciphers have a higher degree of performance. A balance of the two can often be used—SSL/TLS is a perfect example. SSL/TLS most commonly runs in a mode that utilizes both public key and shared key encryption algorithms. The public key algorithm is used to exchange the shared key in a safe manner, and this shared key then is used for all of the bulk encryption operations that follow the session. It is also important to note that different algorithms perform differently.

If performance is a factor for applications, the careful selection of encryption types and algorithms allows the application to meet performance requirements. Alternately, there are hardware components available to offload and increase performance of various encryption operations. These components come in many form factors and can be utilized by the application software.
Segregation of Data and Privileges

In conjunction with access control (above), how data is organized within the application can add or detract from its security. This flaw manifests itself when the application has no central mechanism for accessing sensitive data and when the management of sensitive data is distributed across many components and modules within the application. This distribution of sensitive data makes access control very difficult. It also allows for multiple points of vulnerability—each module or component that manages sensitive data becomes a potential target.

Applications that work with sensitive information can improve security by segregating access and management of that data to a protected module. This module can implement granular access controls and auditing functionality to assure access is granted only to those components that need it. Centralizing access to sensitive data also allows the application designer to more cleanly and logically organize functionality that may otherwise end up unmanageable when it is distributed across too many components.

The second aspect to isolation and segregation within applications concerns privilege. Most systems have some notion of privilege levels, especially when doing development on Windows and UNIX platforms—and many operations require elevated privileges to execute. Common mistakes in this area are:

1. Running the application in an elevated privilege level at all times (as the "root" user on UNIX or as one of the administrative accounts on Windows).
2. Failure to determine which actions truly require elevated privileges. Most operations within an application can be done without the need for elevated privileges.

One solution often used today is the separation of privileged actions. There are a few ways to accomplish this:

1. If possible, isolate privileged operations to initialization time to start with elevated privileges; then drop them once they are complete.
2. If elevated privileges are required at various points during the normal operation of an application, the privileged operations should be isolated from the non-privileged operations. Separate threads or processes then can be used to isolate and execute operations. Combined with the appropriate authentication and access control (above), privileged operations can be implemented and managed safely.

In short, it is vital to limit privileged functionality to a minimum and to keep sensitive data managed. Designing applications with this in mind can reduce the potential vulnerability and allow for better auditing within the application to determine when a problem has occurred.
Error Handling

Error handling is both an engineering and security challenge; how an application behaves individually and in conjunction with other applications can result in stronger or weaker security. An application that has defined constraints and safely handles error conditions can mean the difference between a resilient environment and one that crashes completely.

Error handling is an aspect of application design that is often forgotten or ignored. If a framework for handling errors is not designed, an application may end up with a different scheme for each developer who works on the project. Components of error handling can include:

1. Definition of error types: processing, runtime, security violations, program bugs/assertions.
2. Definition of severity levels: informational, warnings, catastrophic issues.
3. Logging and auditing: centralized auditing with modular logging components such as file, e-mail, and cell phone.
4. Defined responses to error types and levels: issue a warning, stop a component, restart a service, shut down the application, notify an administrator.

The design of an application's error handling capabilities is further strengthened when the functional requirements include negative scenarios; see the section on thinking like the enemy, above. Providing a framework for error handling creates more predictable and easily used applications. It resolves any difficulties that arise from individual developer styles and forces the designer to outline the constraints and limits within the application. A framework for error handling also provides greater clarity and understanding when anomalies do occur.
Testing for Security

One final aspect that people often fail to recognize is the importance of testing as it relates to security. Three components of testing for security are:

1. Functional verification
2. Constraint evaluation
3. Border cases and attacks

Functional verification is the most prevalent form of testing and is most often what is meant when people refer to testing applications. Just as one creates tests for their functional requirements, it is equally important to devise tests for those requirements established for undesired behavior and error conditions—the constraints and limits of the application. Each of the conditions and responses defined for the behavior of the application should be rung out and verified.

Border tests can be thought of in the following manner:

1. Testing interfaces to the application: APIs, network, and user—the physical borders.
2. Testing the borders of data processing: Multiple combinations of imperfect data that will be processed by the application. These can include valid ranges of data values, unexpected types, and randomly generated data.

There are a number of tools available to test an application's security. These include code analyzers, modeling tools, and stress testing tools such as fuzzers, which help identify many software vulnerabilities and coding issues.

The combination of testing that includes defined functionality and constraint evaluation, as well as stress testing that pushes the limits and boundaries of an application, help improve the security before it becomes deployed in critical environments.

Security in and of an application does not have to be an overwhelming task. By considering the security aspects of an application at all stages, as early as basic functional requirements, one can weave security into all areas of the application; doing so results in a cumulative and strong level of security strength, resiliency, and quality. Effort spent during the design phases looking at the various layers of the application and how one hopes people will and will not use the application sets the foundation for functionality that both meets the needs of users and withstands all anomalies that occur.

Proper application of security technologies such as authentication, access control, and encryption can assure a higher degree of safety in untrustworthy environments. An understanding of worst-case scenario events, handling errors, and compartmentalizing sensitive data and operations within the application can solidify the strength of an application. Finally, taking some time to test and verify constraints, functionality, and security will assure a level of confidence with the developers and users alike. Keep security in mind to create useful—and safe—applications.
About the Author

Chad Cook has spent over a dozen years in Information Security that include both product engineering and IT services. Chad has developed IT service security strategies, networks, and policies for organizations including BBN and GTE Internetworking, Infolibria, and the international security consulting firm, @stake/Symantec. He has architected and developed security technology for award-winning networking, security, and financial products sold worldwide, including core routers, edge devices, utility hosting systems, and Web services security devices and high-performance systems. Chad has nine patents applied for and pending on security analysis, modeling techniques, and encryption processing acceleration.

Currently, Chad is the VP of Information Security at Lime Group, a New York securities and brokerage organization, where he leads product architecture, infrastructure security, and compliance efforts. Prior to Lime Group, he designed and developed security risk management and threat modeling products as CTO at Black Dragon Software. Chad has held lead engineering and security positions developing products at BBN, GTE, and a number of small companies. Chad is an internationally published author on security topics having contributed to two books, Maximum Security, 3rd and 4th editions, has been featured in numerous articles and also has written articles for Symantec's SecurityFocus.com and numerous online publications.

10 Commandments for Java Developers

There are many standards and best practices for Java Developers out there. This article outlines ten most basic rules that every developer must adhere to and the disastrous outcomes that can follow if these rules are not followed.

1. Add comments to your code. – Everybody knows this, but somehow forgets to follow it. How many times have you "forgotten" to add comments? It is true that the comments do not literally contribute to the functionality of a program. But time and time again you return to the code that you wrote two weeks ago and, for the life of you, you cannot remember what it does! You are lucky if this uncommented code is actually yours. In those cases something may spark your memory. Unfortunately most of the time it is somebody else's, and many times the person is no longer with the company! There is a saying that goes "one hand washes the other." So let's be considerate to one another (and ourselves) and add comments to your code.

2. Do not complicate things. – I have done it before and I am sure all of you have. Developers tend to come up with complicated solutions for the simplest problems. We introduce EJBs into applications that have five users. We implement frameworks that an application just does not need. We add property files, object-oriented solutions, and threads to application that do not require such things. Why do we do it? Some of us just do not know any better, but some of us do it on purpose to learn something new, to make it interesting for ourselves. For those who do not know any better, I recommend reaching out to the more experienced programmers for advice. And to those of us that are willing to complicate the design of an application for personal gains, I suggest being more professional.

3. Keep in Mind – "Less is more" is not always better. – Code efficiency is a great thing, but in many situations writing less lines of code does not improve the efficiency of that code. Let me give you a "simple" example:

if(newStatusCode.equals("SD") && (sellOffDate == null ||
todayDate.compareTo(lastUsedDate)>0)) ||
(newStatusCode.equals("OBS") && (OBSDate == null ||
newStatusCode = "NYP";

How easy is it to figure out what this "if" condition is doing? Now imagine that whoever wrote this code, did not follow rule number 1 – Add comments to your code.

Wouldn't it be much easier if we could separate this condition into two separate if statements? Now, consider this revised code:

if(newStatusCode.equals("SD") && (sellOffDate == null ||
newStatusCode = "NYP";
if(newStatusCode.equals("OBS") && (OBSDate == null ||
newStatusCode = "NYP";

Isn't it much more readable? Yes, we have repeating statements. Yes, we have one extra "IF" and two extra curly braces, but the code is much more readable and understandable!

4. No hard coding please. – Developers often forget or omit this rule on purpose because we are, as usual, crunched for time. But maybe if we had followed this rule, we would not have ended up in the situation that we are in. How long does it take to write one extra line of code that defines a static final variable?

Here is an example:

public class A {

public static final String S_CONSTANT_ABC = "ABC";

public boolean methodA(String sParam1){

if (A.S_CONSTANT_ABC.equalsIgnoreCase(sParam1)){
return true;
return false;

Now every time we need to compare literal "ABC" with some variable, we can reference A.S_CONSTANT_ABC instead of remembering what the actual code is. It is also much easier to modify this constant in one place rather then looking for it though out all of the code.

5. Do not invent your own frameworks. – There are literally thousands of frameworks out there and most of them are open-source. Many of these frameworks are superb solutions that have been used in thousands of applications. We need to keep up to date with the new frameworks, at least superficially. One of the best and most obvious examples of a superb widely used framework is Struts. This open source web framework is a perfect candidate to be used in web-based applications. Please do not come up with your own version of Struts, you will die trying. But you must remember rule number 3 – Do not complicate things. If the application that you are developing has 3 screens – please, do not use Struts, there isn't much "controlling" required for such an application.

6. Say no to Print lines and String Concatenations. – I know that for debugging purposes, developers like to add System.out.println everywhere we see fit. And we say to ourselves that we will delete these later. But we often forget to delete these lines of code or we do not want to delete them. We use System.out.println to test, why would we be touching the code after we have tested it? We might remove a line of code that we actually need! Just so that you do not underestimate the damage of System.out.println, consider the following code:

public class BadCode {
public static void calculationWithPrint(){
double someValue = 0D;
for (int i = 0; i <>
System.out.println(someValue = someValue + i);
public static void calculationWithOutPrint(){

double someValue = 0D;
for (int i = 0; i <>
someValue = someValue + i;

public static void main(String [] n) {

In the figure below, you can observe that method calculationWithOutPrint() takes 0.001204 seconds to run. In comparison, it takes a staggering 10.52 seconds to run the calculationWithPrint() method.

(If you would like to know how to produce a table like this, please read my article entitled "Java Profiling with WSAD" Java Profiling with WSAD )

The best way to avoid such CPU waste is to introduce a wrapper method that looks something like this:

public class BadCode {

public static final int DEBUG_MODE = 1;
public static final int PRODUCTION_MODE = 2;

public static void calculationWithPrint(int logMode){
double someValue = 0D;
for (int i = 0; i <>
someValue = someValue + i;
myPrintMethod(logMode, someValue);

public static void myPrintMethod(int logMode, double value) {
if (logMode > BadCode.DEBUG_MODE) { return; }
public static void main(String [] n) {

String concatenation is another CPU waster. Consider example below:

public static void concatenateStrings(String startingString) {
for (int i = 0; i <>
startingString = startingString + startingString;

public static void concatenateStringsUsingStringBuffer(
String startingString) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i <>

In the following figure you can see that the method that uses StringBuffer takes .01 seconds to execute where as the methods that use string concatenation takes .08 seconds to execute. The choice is obvious.

7. Pay attention to the GUI. – No matter how absurd it sounds; I repeatedly observe that GUI is as important to the business clients as functionality and performance. The GUI is an essential part of a successful application. Very often IT management tends to overlook the importance of GUI. Many organizations save money by not hiring web designers who have experience in design of "user-friendly" applications. Java developers have to rely on their own HTML skills and their limited knowledge in this area. I have seen too many applications that are "computer friendly" rather then "user friendly". Very rarely I have seen developers that are proficient in both software development and GUI development. If you are this unlucky Java developer who has been assigned to create an application interface, you should follow these three rules:

1. Do not reinvent the wheel. Look for existing applications that have similar interface requirements.
2. Create a prototype first. This is a very important step. The clients like to see what they are going to get. It is better for you also because you are going to get their input before you go all out and create an application interface that will leave the clients cold.
3. Put the user's hat on. In other words, inspect the application requirements from the user's perspective. For example, a summary screen can be created with paging and without. As a software developer, it might be temping for you to omit paging from the application because it is so much less complicated. But, from the client's perspective, it might not be the best solution because the summary results can hold hundreds of rows of data.

8. Always Prepare Document Requirements. – Every business requirement must be documented. This could be true in some fairy tale, but it is far from that in the real world. No matter how time-pressed your development is, no matter how tight the deadlines, you must always make sure that every business requirement is documented.

9. Unit-test. Unit-test. Unit-test. – I am not going to go into any details as to what is the best way to unit-test your code. I am just going to say that that it must be done. This is the most basic rule of programming. This is one rule that, above all, cannot be omitted. It would be great if your fellow developer could create and execute a test plan for your code, but if that is not possible, you must do it yourself. When creating a unit test plan, follow these basic rules:

1. Write the unit test before writing code for class it tests.
2. Capture code comments in unit tests.
3. Test all the public methods that perform an "interesting" function (that is, not getters and setters, unless they do their getting and setting in some unique way).

10. Remember – quality, not quantity. - Do not stay late (when you do not have to). I understand that sometimes production problems, urgent deadlines, and unexpected events might prevent us from leaving work on time. But, managers do not appreciate and reward their employees because they stay late on regular basis, they appreciate them because they do quality work. If you follow the rules that I outline above, you will find yourself producing less buggy and more maintainable code. That is the most important part of your job.

Securing Struts Applications

Most Web applications require certain aspects of the system to be secured in some manner. Security requirements are often specified at both the system and functional levels. System requirements may dictate, for example, that entry of sensitive information should be performed over a secure HTTP connection (HTTPS). On a higher level, functional requirements may dictate that only users with administrative privileges can access certain pages and menu items. From a developer's perspective, the critical task is to identify which of the requirements can be satisfied using standard security mechanisms, and which requirements require a customized security solution. Quite often, security requirements dictate some sort of customization. In some cases, you can use a combination of standard security mechanisms and customization to achieve the desired security policy.
Levels of Security

Security is a fairly broad topic and may encompass everything from encryption to personalization, depending on how 'security' is defined. This chapter focuses on the levels of security that you can implement to secure your Struts applications, beginning in this section with an overview of the various security levels. That is followed by sections that look in depth at using container-managed security and application-managed security, the two primary ways to secure your Struts applications.

* Transport-level security using HTTPS
* authentication and authorization
* Role-based access control
* Container-managed security
* Application-managed security

Some aspects of personalization will also be covered, specifically some techniques for hiding or displaying content based on a user's authorization.
Providing Secure Communications

Data can be securely transmitted by using HTTP over Secure Socket Layer (referred to as HTTPS). HTTPS secures data by encrypting the protocol at the transport level. In other words, the entire HTTP conversation between the client browser and the Web server is encrypted. Struts applications, like most Web applications, can send data over HTTPS without modification.

HTTPS does impact performance, however. There is an order of magnitude of performance penalty when using HTTPS. To reduce the impact on performance, it is common for applications to switch the protocol between HTTP and HTTPS. The typical scenario uses the HTTPS protocol for application login and submission of sensitive data. Once the data is entered, the protocol is switched back to HTTP. While on the surface this seems like a good approach, it leaves open a serious security hole whereby the user's session can be hijacked. Sensitive user information, such as a credit card number, may be stored in that session. A network snoop could use the session ID to spoof a valid user session. Due to this risk, container-managed security does not support protocol switching. However, if you need protocol switching and can accept the security risks, there are mechanisms for doing so that integrate with Struts.
Authentication and Authorization

Authentication is the process of proving to an application that you are who you say you are. For Web applications, this process is most commonly associated with entering a username and password. If you are registered as a user of the application and you provide a valid password, the application allows access to privileged features of the application. In contrast, if you cannot provide valid credentials, you are allowed access only to the public areas of the site. In fact, many Web applications may only allow authenticated access-with the only public page being the login screen. Authentication can be provided through custom coding for the application, or by using container-managed security services.

Authorization is how the application determines which aspects of the Web application you are allowed to access. Generally speaking, determining a user's authorization requires the user to first be authenticated. Once authenticated, application-provided or container-managed security can be used to determine a user's authorization.
Role-based Access Control

Role-based access control (RBAC) is a common scheme for implementing authorization. Users are assigned roles through a container-specific means. When a user is authenticated, the user's roles are associated with the HTTP request. Given this information, access to certain pages or user interface components can be allowed or disallowed based on the user's roles. In most cases, a user is allowed to have multiple roles. However, roles are typically flat; that is, there is no hierarchical relationship between roles.
Container- vs. Application-Managed Security

Servlet containers provide security as specified by the servlet specification. Container-managed security allows the developer to declaratively specify how authentication is to be performed and how authorization is to be granted. Container-managed security provides an easy, unobtrusive way of adding security to an application. This mechanism of implementing security provides the following benefits:

* It is declarative. Authentication and authorization are specified in the web.xml file. Container-specific details, such as the security realm, typically are configured in server-specific XML configuration files.

* It supports multiple authentication schemes, such as password authentication, FORM-based authentication, authentication using encrypted passwords, and authentication using client-side digital certificates.

* Using container-specific security realms, user data can be provided by a variety of stores, including flat files, relational databases, and Lightweight Directory Access Protocol (LDAP) servers.

* Redirects are handled automatically. In other words, the container determines when a user is accessing a protected URL, prompts for user credentials, and, if authenticated, redirects to the requested page. This is a powerful mechanism, particularly for applications that publish links to protected pages in e-mail communications.

Containers are, however, somewhat limiting because of the following:

* The implementation of container-managed security varies by container. An application using container-managed security generally requires modification at some level when ported from one application server to another.

* The login flow does not allow easy custom processing of login requests. In other words, additional processing cannot be performed in the authentication process.

* Authorization can only use a flat, role-based approach. Access to Web pages cannot be granted based on multiple factors, for example, a managerial level and a department number.

* FORM-based login forces a workflow that uses a separate page for login. This limits the flexibility of the application.

* Container-managed authentication requires changes to the application server's configuration that may not be allowed in a hosted environment.

These limitations can be overcome by using application-managed security. However, using application-managed security means that custom code must be designed and written. The decision of which approach to take should be driven by the requirements. While container-managed security is simpler to implement, it does restrict the flexibility of your security policy. One container's security implementation may be different from another's, making your application less portable. Also, container-managed security limits you to a specific login workflow that may not be what you want for your application.

Application-managed security, on the other hand, allows you to implement your security policy as needed at the price of requiring more custom code. Struts mitigates this problem by allowing for customized role processing via a custom request processor. Also, servlet filters can be used to apply across-the-board security policies. Cookies can be used to persist user login information between sessions. In addition, there are Struts extensions that permit finer-grained control of the use of HTTPS.

One last point: there is a somewhat hybrid approach that allows programmatic access to the methods that are usually only available when using container-managed security.