Search This Blog

Wednesday, November 11, 2009

JSP Actions

In this section we will explain you about JSP Action tags and in the next section we will explain the uses of these tags with examples. We will also show how to use JSP Action Tags in the JSP application.

What is JSP Actions?

Servlet container provides many built in functionality to ease the development of the applications. Programmers can use these functions in JSP applications. The JSP Actions tags enables the programmer to use these functions. The JSP Actions are XML tags that can be used in the JSP page.

Here is the list of JSP Actions:
jsp:include
The jsp:include action work as a subroutine, the Java servlet temporarily passes the request and response to the specified JSP/Servlet. Control is then returned back to the current JSP page.

jsp:param
The jsp:param action is used to add the specific parameter to current request. The jsp:param tag can be used inside a jsp:include, jsp:forward or jsp:params block.

jsp:forward
The jsp:forward tag is used to hand off the request and response to another JSP or servlet. In this case the request never return to the calling JSP page.

jsp:plugin
In older versions of Netscape Navigator and Internet Explorer; different tags is used to embed applet. The jsp:plugin tag actually generates the appropriate HTML code the embed the Applets correctly.

jsp:fallback
The jsp:fallback tag is used to specify the message to be shown on the browser if applets is not supported by browser.
Example:

Unable to load applet




jsp:getProperty
The jsp:getPropertyB is used to get specified property from the JavaBean object.

jsp:setProperty
The jsp:setProperty tag is used to set a property in the JavaBean object.

jsp:useBean
The jsp:useBean tag is used to instantiate an object of Java Bean or it can re-use existing java bean object.

In the next sections we will learn how to use these JSP Actions (JSP Action tags).

JSP Architecture

JSP Architecture JSP ARCHITECTURE J PS pages are high level extension of servlet and it enable the developers to embed java code in html pages. JSP files are finally compiled into a servlet by the JSP engine. Compiled servlet is used by the engine

JSP pages are high level extension of servlet and it enable the developers to embed java code in html pages. JSP files are finally compiled into a servlet by the JSP engine. Compiled servlet is used by the engine to serve the requests.

javax.servlet.jsp package defines two interfaces:

JSPPage

HttpJspPage

These interfaces defines the three methods for the compiled JSP page. These methods are:
jspInit()
jspDestroy()
_jspService(HttpServletRequest request,HttpServletResponse response)


In the compiled JSP file these methods are present. Programmer can define jspInit() and jspDestroy() methods, but the _jspService(HttpServletRequest request,HttpServletResponse response) method is generated by the JSP engine.

Tuesday, November 10, 2009

JavaServer Pages

JavaServer Pages (JSP) technology is the Java platform technology for delivering dynamic content to web clients in a portable, secure and well-defined way. The JavaServer Pages specification extends the Java Servlet API to provide web application developers with a robust framework for creating dynamic web content on the server using HTML, and XML templates, and Java code, which is secure, fast, and independent of server platforms. JSP has been built on top of the Servlet API and utilizes Servlet semantics. JSP has become the preferred request handler and response mechanism. Although JSP technology is going to be a powerful successor to basic Servlets, they have an evolutionary relationship and can be used in a cooperative and complementary manner.

Servlets are powerful and sometimes they are a bit cumbersome when it comes to generating complex HTML. Most servlets contain a little code that handles application logic and a lot more code that handles output formatting. This can make it difficult to separate and reuse portions of the code when a different output format is needed. For these reasons, web application developers turn towards JSP as their preferred servlet environment.
Evolution of Web Applications

Over the last few years, web server applications have evolved from static to dynamic applications. This evolution became necessary due to some deficiencies in earlier web site design. For example, to put more of business processes on the web, whether in business-to-consumer (B2C) or business-to-business (B2B) markets, conventional web site design technologies are not enough. The main issues, every developer faces when developing web applications, are:

1. Scalability - a successful site will have more users and as the number of users is increasing fastly, the web applications have to scale correspondingly.

2. Integration of data and business logic - the web is just another way to conduct business, and so it should be able to use the same middle-tier and data-access code.

3. Manageability - web sites just keep getting bigger and we need some viable mechanism to manage the ever-increasing content and its interaction with business systems.

4. Personalization - adding a personal touch to the web page becomes an essential factor to keep our customer coming back again. Knowing their preferences, allowing them to configure the information they view, remembering their past transactions or frequent search keywords are all important in providing feedback and interaction from what is otherwise a fairly one-sided conversation.

Apart from these general needs for a business-oriented web site, the necessity for new technologies to create robust, dynamic and compact server-side web applications has been realized. The main characteristics of today's dynamic web server applications are as follows:

1. Serve HTML and XML, and stream data to the web client

2. Separate presentation, logic and data

3. Interface to databases, other Java applications, CORBA, directory and mail services

4. Make use of application server middleware to provide transactional support.

5. Track client sessions

Now let us have a look on the role of Java technology and platform in this regard.
Java's Role for Server Applications

Sun Microsystems, having consulted many expert partners from other related IT industries, has come out with a number of open APIs for the technologies and services on server side. This collection of APIs is named as Java 2 Enterprise Edition (J2EE). The J2EE specification provides a platform for enterprise applications, with full API support for enterprise code and guarantees of portability between server implementations. Also it brings a clear division between code which deals with presentation, business logic and data.

The J2EE specification meets the needs of web applications because it provides:

1. Rich interaction with a web server via servlets and built-in support for sessions available in both servlets and EJBs.

2. The use of EJBs to mirror the user interaction with data by providing automatic session and transaction support to EJBs operating in the EJB server.

3. Entity EJBs to represent data as an object and seamless integration with the Java data access APIs

4. Flexible template-based output using JSP and XML

This family of APIs mean that the final web page can be generated from a user input request, which was processed by a servlet or JSP and a session EJB, which represents the user's session with the server, using data extracted from a database and put into an entity EJB. Thus, the Java revolution of portable code and open APIs is married with an evolution in existing products such as database, application, mail and web servers. The wide availability of products to run Java applications on the server has made this a fast-moving and very competitive market, but the essential compatibility through specifications, standard APIs and class libraries has held. This makes server-side Java a very exciting area.
JavaServer Pages - An Overview

The JavaServer Pages 1.2 specification provides web developers with a framework to build applications containing dynamic web content such as HTML, DHTML, XHTML and XML. A JSP page is a text based document containing static HTML and dynamic actions which describe how to process a response to the client in a more powerful and flexible manner. Most of a JSP file is plain HTML but it also has, interspersed with it, special JSP tags.

There are many JSP tags such as:
JSP directive denoted by <%@, 2. scriplets indicated by <% ... %> tags and
directive includes the contents of the file sample.html in the response at that point.

To process a JSP file, we need a JSP engine that can be connected with a web server or can be accommodated inside a web server. Firstly when a web browser seeks a JSP file through an URL from the web server, the web server recognizes the .jsp file extension in the URL requested by the browser and understands that the requested resource is a JavaServer Page. Then the web server passes the request to the JSP engine. The JSP page is then translated into a Java class, which is then compiled into a servlet.

This translation and compilation phase occurs only when the JSP file is requested for the first time, or if it undergoes any changes to the extent of getting retranslated and recompiled. For each additional request of the JSP page thereafter, the request directly goes to the servlet byte code, which is already in memory. Thus when a request comes for a servlet, an init() method is called when the Servlet is first loaded into the virtual machine, to perform any global initialization that every request of the servlet will need. Then the individual requests are sent to a service() method, where the response is put together. The servlet creates a new thread to run service() method for each request. The request from the browser is converted into a Java object of type HttpServletRequest, which is passed to the Servlet along with an HttpServletResponse object that is used to send the response back to the browser. The servlet code performs the operations specified by the JSP elements in the .jsp file.
The Components of JSPs

JSP syntax is almost similar to XML syntax. The following general rules are applicable to all JSP tags.

1. Tags have either a start tag with optional attributes, an optional body, and a matching end tag or they have an empty tag possibly with attributes.

2. Attribute values in the tag always appear quoted. The special strings ' and " can be used if quotes are a part of the attribute value itself.

Any whitespace within the body text of a document is not significant, but is preserved, which means that any whitespace in the JSP being translated is read and preserved during translation into a servlet.

The character \ can be used as an escape character in a tag, for instance, to use the % character, \% can be used.

JavaServer Pages are text files that combine standard HTML and new scripting tags. JSPs look like HTML, but they get compiled into Java servlets the first time they are invoked. The resulting servlet is a combination of HTML from the JSP file and embedded dynamic content specified by the new tags. Everything in a JSP page can be divided into two categories:

1. Elements that are processed on the server

2. Template data or everything other than elements, that the engine processing the JSP engines.

Element data or that part of the JSP which is processed on the server, can be classified into the following categories:

1. Directives

2. Scripting elements

3. Standard actions

JSP directives serve as messages to the JSP container from the JSP. They are used to set global values such as class declaration, methods to be implemented, output content type, etc. They do not produce any output to the client. All directives have scope of the entire JSP file. That is, a directive affects the whole JSP file, and only that JSP file. Directives are characterized by the @ character within the tag and the general syntax is:

The three directives are page, include and taglib.

Scripting elements are used to include scripting code (Java code) within the JSP. They allow to declare variables and methods, include arbitrary scripting code and evaluate an expression. The three types of scripting element are: Declaration, Scriptlets and Expressions.

A declaration is a block of Java code in a JSP that is used to define class-wide variables and methods in the generated class file. Declarations are initialized when the JSP page is initialized and have class scope. Anything defined in a declaration is available throughout the JSP, to other declarations, expressions or code.

A scriptlet consists of one or more valid Java statements. A scriptlet is a block of Java code that is executed at request-processing time. A scriptlet is enclosed between "<%" and "%>". What the scriptlet actually does depends on the code, and it can produce output into the output stream to the client. Multiple scriptlets are combined in the compiled class in the order in which they appear in the JSP. Scriptlets like any other Java code block or method, can modify objects inside them as a result of method invocations.

An expression is a shorthand notation for a scriptlet that outputs a value in the response stream back to the client. When the expression is evaluated, the result is converted to a string and displayed, An expression is enclosed within <%= and %> "<%=" and "%>". If any part of expression is an object, the conversion is done using the toString() method of the object.

Standard actions are specific tags that affect the runtime behavior of the JSP and affect the response sent back to the client. The JSP specification lists some standard action types to be provided by all containers, irrespective of the implementation. Standard actions provide page authors with some basic functionality to exploit; the vendor is free to provide other actions to enhance behavior.
How JSP and JSP Container function

A JSP page is executed in a JSP container or a JSP engine, which is installed in a web server or in a application server. When a client asks for a JSP page the engine wraps up the request and delivers it to the JSP page along with a response object. The JSP page processes the request and modifies the response object to incorporate the communication with the client. The container or the engine, on getting the response, wraps up the responses from the JSP page and delivers it to the client. The underlying layer for a JSP is actually a servlet implementation. The abstractions of the request and response are the same as the ServletRequest and ServletResponse respectively. If the protocol used is HTTP, then the corresponding objects are HttpServletRequest and HttpServletResponse.

The first time the engine intercepts a request for a JSP, it compiles this translation unit (the JSP page and other dependent files) into a class file that implements the servlet protocol. If the dependent files are other JSPs they are compiled into their own classes. The servlet class generated at the end of the translation process must extend a superclass that is either

1. specified by the JSP author through the use of the extends attribute in the page directive or

2. is a JSP container specific implementation class that implements javax.servlet.jsp.JspPage interface and provides some basic page specific behavior.

Since most JSP pages use HTTP, their implementation classes must actually implement the javax.servlet.jsp.HttpJspPage interface, which is a sub interface of javax.servlet.jsp.JspPage.

The javax.servlet.jsp.JspPage interface contains two methods:

1. public void jspInit() - This method is invoked when the JSP is initialized and the page authors are free to provide initialization of the JSP by implementing this method in their JSPs.

2. public void jspDestroy() - This method is invoked when the JSP is about to be destroyed by the container. Similar to above, page authors can provide their own implementation.

The javax.servlet.jsp.HttpJspPage interface contains one method:

public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

This method generated by the JSP container is invoked, every time a request comes to the JSP. The request is processed and the JSP generates appropriate response. This response is taken by the container and passed back to the client.
JSP Architecture

There are two basic ways of using the JSP technology. They are the client/server (page-centric) 2-tier approach and the N-tier approach (dispatcher).

The Page-Centric Approach

Applications built using a client-server (2-tier) approach consist of one or more application programs running on client machines and connecting to a server-based application to work. With the arrival of Servlets technology, 2-tier applications could also be developed using Java programming language. This model allows JSPs or Servlets direct access to some resource such as database or legacy application to service a client's request. The JSP page is where the incoming request is intercepted, processed and the response sent back to the client. JSPs differ from Servlets in this scenario by providing clean code, separating code from the content by placing data access in EJBs. Even though this model makes application development easier, it does not scale up well for a large number of simultaneous clients as it entails a significant amount of request processing to be performed and each request must establish or share a potentially scarce/expensive connection to the resource in question.

Page-view - This basic architecture involves direct request invocations to a server page with embedded Java code, and markup tags which dynamically generate output for substitution within the HTML. This approach has been blessed a number of benefits. It is very straightforward and is a low-overhead approach from a developerment perspective. All the Java code may be embedded within the HTML, so changes are confined to a very limited area, reducing complexity drastically.

The big trade-off here is in the level of sophistication. As the scale of the system grows, some limitations begin to surface, such as bloating of business logic code in the page instead of factoring forward to a mediating Servlet or factoring back to a worker bean. It is a fact that utilizing a Servlet and helper beans helps to separate developer roles more cleanly and improves the potential for code reuse.

Page-view with bean - This pattern is used when the above architecture becomes too cluttered with business-related code and data access code. The Java code representing the business logic and simple data storage implementation in the previous model moves from the JSP to the JavaBean worker. This refactoring leaves a much cleaner JSP with limited Java code, which can be comfortably owned by an individual in a web-production role, since it encapsulates mostly markup tags.

The Dispatcher Approach

In this approach, a Servlet or JSP acts as a mediator or controller, delegating requests to JSP pages and JavaBeans. There are three different architectures. They are mediator-view, mediator-composite view and service to workers.

In an N-tier application, the server side of the architecture is broken up into multiple tiers. In this case, the application is composed of multiple tiers, where the middle tier, the JSP, interacts with the back end resources via another object or EJBs component. The Enterprise JavaBeans server and the EJB provide managed access to resources, support transactions and access to underlying security mechanisms, thus addressing the resource sharing and performance issues of the 2-tier approach.

The first step in N-tiered application design should be identifying the correct objects and their interaction and the second step is identifying the JSPs or Servlets. These are divided into two categories.

Front end JSPs or Servlets manage application flow and business logic evaluation. They act as a point to intercept the HTTP requests coming from the users. They provide a single entry point to an application, simplifying security management and making application state easier to maintain.

Presentation JSPs or Servlets generate HTML or XML with their main purpose in life being presentation of dynamic content. They contain only presentation and rendering logic.

These categories resemble to the Modal-View design pattern, where the front-end components is the model and the presentation component the view. In this approach, JSPs are used to generate the presentation layer and either JSPs or Servlets to perform process-intensive tasks. The front-end component acts as the controller and is in charge of the request processing and the creation of any beans or objects used by the presentation JSP, as well as deciding, depending on the user's actions, which JSP to forward this request to. There is no processing logic within the presentation JSP itself and it simply responsible for retrieving any objects or beans that may have been previously created by the Servlet and extracting the dynamic content for insertion within static templates.
Benefits of JSP

One of the main reasons why the JavaServer Pages technology has evolved into what it is today and it is still evolving is the overwhelming technical need to simplify application design by separating dynamic content from static template display data. Another benefit of utilizing JSP is that it allows to more cleanly separate the roles of web application/HTML designer from a software developer. The JSP technology is blessed with a number of exciting benefits, which are chronicled as follows:

1. The JSP technology is platform independent, in its dynamic web pages, its web servers, and its underlying server components. That is, JSP pages perform perfectly without any hassle on any platform, run on any web server, and web-enabled application server. The JSP pages can be accessed from any web server.

2. The JSP technology emphasizes the use of reusable components. These components can be combined or manipulated towards developing more purposeful components and page design. This definitely reduces development time apart from the At development time, JSPs are very different from Servlets, however, they are precompiled into Servlets at run time and executed by a JSP engine which is installed on a Web-enabled application server such as BEA WebLogic and IBM WebSphere.
Conclusion

JSP and Servlets are gaining rapid acceptance as means to provide dynamic content on the Internet. With full access to the Java platform, running from the server in a secure manner, the application possibilities are almost limitless. When JSPs are used with Enterprise JavaBeans technology, e-commerce and database resources can be further enhanced to meet an enterprise's needs for web applications providing secure transactions in an open platform. J2EE technology as a whole makes it easy to develop, deploy and use web server applications instead of mingling with other technologies such as CGI and ASP. There are many tools for facilitating quick web software development and to easily convert existing server-side technologies to JSP and Servlets.

Many application server vendors are aggressively deploying JSP within their products. This results in developing robust e-commerce applications as JSP provides XML functionality and scalability. By providing a clear separation between content and coding, JSP solves many problems attached with existing server-side applications.


Introduction to JSP

Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server side scripting support for creating database driven web applications. JSP enable the developers to directly insert java code into jsp file, this makes the development process very simple and its maintenance also becomes very easy. JSP pages are efficient, it loads into the web servers memory on receiving the request very first time and the subsequent calls are served within a very short period of time.

In today's environment most web sites servers dynamic pages based on user request. Database is very convenient way to store the data of users and other things. JDBC provide excellent database connectivity in heterogeneous database environment. Using JSP and JDBC its very easy to develop database driven web application.

Java is known for its characteristic of "write once, run anywhere." JSP pages are platform independent. Your port your .jsp pages to any platform.

Installing JSP
First of all download JavaServer Web Development Kit (JSWDK1.0.1) from http://java.sun.com/products/servlet/download.html. JSWDK comes with full documentation and it's very easy to install, so the installation process is not mentioned here. The JSWDK is the official reference implementation of the servlet 2.1 and JSP 1.0 specifications. It is used as a small stand-alone server for testing servlets and JSP pages before they are deployed to a full Web server that supports these technologies. It is free and reliable, but takes quite a bit of effort to install and configure.

Other Servers that support JSP
Apache Tomcat.
Tomcat is the official reference implementation of the servlet 2.2 and JSP 1.1 specifications. It can be used as a small stand-alone server for testing servlets and JSP pages, or can be integrated into the Apache Web server.
Allaire JRun.
JRun is a servlet and JSP engine that can be plugged into Netscape Enterprise or FastTrack servers, IIS, Microsoft Personal Web Server, older versions of Apache, O’Reilly’s WebSite, or StarNine WebSTAR.
New Atlanta’s ServletExec.
ServletExec is a fast servlet and JSP engine that can be plugged into most popular Web servers for Solaris, Windows, MacOS, HP-UX and Linux. You can download and use it for free, but many of the advanced features and administration utilities are disabled until you purchase a license.
Gefion's LiteWebServer (LWS). LWS is a small free Web server that supports servlets version 2.2 and JSP 1.1.
GNU JSP. free, open source engine that can be installed on apache web server.
PolyJSP. PolyJsp is based on XML/XSL and has been designed to be extensible. Now supports WebL
JRUN. Available for IIS server.
WebSphere. IBM's WebSphere very large application server now implements JSP.



Developing first JSP
Java Server Pages are save with .jsp extension. Following code which generates a simple html page.

Execute the example.

First JSP page.


<%="Java Developers Paradise"%>


<%="Hello JSP"%>




In jsp java codes are written between '<%' and '%>' tags. So it takes the following form : <%= Some Expression %> In this example we have use
<%="Java Developers Paradise"%>

introduction to java

This section introduces you the Java programming language. These days Java programming language is being used for programming web applications. It is also widely used for mobile and electronic items.
What is Java?
Java is a high-level object-oriented programming language developed by the Sun Microsystems. Though it is associated with the World Wide Web but it is older than the origin of Web.

Java as an Internet Language
Java is an object oriented language and a very simple language. Because it has no space for complexities. At the initial stages of its development it was called as OAK. OAK was designed for handling set up boxes and devices.

Java as general purpose language
Java is an Object oriented application programming language developed by Sun Microsystems.

Java Features

Case sensitivity
What is case sensitivity: Case sensitivity is the mechanism in which words can be differ in meaning based on different use of uppercase and lowercase letters.

Java is Simple and platform Independent
The concept of Write-once-run-anywhere (known as the Platform independent) is one of the important key feature of java language that makes java as the most powerful language.

Java Enabled browsers
Java language is the most powerful language and is widely used in the web application. Today most of the web browser are java compatible.

Java Tools

Java Compiler
To commence with Java programming, we must know the significance of Java Compiler.

Java Interpreter
We can run Java on most platforms provided a platform must has a Java interpreter.

Java Debugger
Java debugger helps in finding and the fixing of bugs in Java language programs.

Java Header File Generator
In Java programming we need to implement some native methods. To implement these methods Javah generates C header and source files that are used by C programs to reference an Object's instance variables from native source code.

JavaDoc
This tool is used to generate API documentation into HTML format from Java source code.

Applet Viewer
Applet viewer is a command line program to run Java applets.

java tools

Java Compiler
To commence with Java programming, we must know the significance of Java Compiler.

To commence with Java programming, we must know the significance of Java Compiler. When we write any program in a text editor like Notepad, we use Java compiler to compile it. A Java Compiler javac is a computer program or set of programs which translates java source code into java byte code.

The output from a Java compiler comes in the form of Java class files (with .class extension). The java source code contained in files end with the .java extension. The file name must be the same as the class name, as classname.java. When the javac compiles the source file defined in a .java files, it generates bytecode for the java source file and saves in a class file with a .class extension.

The most commonly used Java compiler is javac, included in JDK from Sun Microsystems.

Following figure shows the working of the Java compiler:


Once the byte code is generated it can be run on any platform using Java Interpreter (JVM). It interprets byte code (.class file) and converts into machine specific binary code. Then JVM runs the binary code on the host machine.

How to use Java Compiler

When you run javac command on the command prompt, it shows the following output.C:\>javac
Usage: javac
where possible options include:
-g Generate all debugging info

-g:none Generate no debugging info

-g:{lines,vars,source} Generate only some debugging info

-nowarn Generate no warnings

-verbose Output messages about what the compiler is doing

-deprecation Output source locations where deprecated APIs are
used

-classpath Specify where to find user class files and
annotation processors

-cp Specify where to find user class files and
annotation processors

-sourcepath Specify where to find input source files

-bootclasspath Override location of bootstrap class files

-extdirs Override location of installed extensions

-endorseddirs Override location of endorsed standards path

-proc:{none,only} Control whether annotation processing and/or
compilation is done.

-processor [,,...]
Names of the annotation processors to run;
bypasses default discovery process

-processorpath Specify where to find annotation processors

-d Specify where to place generated class files

-s Specify where to place generated source files

-implicit:{none,class} Specify whether or not to generate class files
for implicitly referenced files

-encoding Specify character encoding used by source files

-source Provide source compatibility with specified
release

-target Generate class files for specific VM version

-version Version information

-help Print a synopsis of standard options

-Akey[=value] Options to pass to annotation processors

-X Print a synopsis of nonstandard options

-J Pass directly to the runtime system
C:\>



Above output shows the different options of javac tool.

Using java compiler to compile java file:
Following example shows how a Compiler works. It compiles the program and gives the Syntax error, if there is any. Like in this example, we haven't initialized 'a' and we are using it in the next statement as 'int c=a+b'. That is why its showing a syntax error. class A{
public static void main(String[] args){
int a;
int b=2;
int c=a+b;
System.out.println(c);
}
}


Output of program: C:\Program Files\Java\jdk1.6.0_01\bin>javac A.java
A.java:6: variable a might not have been initialized
int c=a+b;
^
1 error

C:\Program Files\Java\jdk1.6.0_01\bin>


Now, lets tweak this example. In this we have initialized 'a' as 'int a =2'. Hence, no syntax error has been detected.class A{
public static void main(String[] args) {
int a=2;
int b=2;
int c=a+b;
System.out.println(c);
}
}


Output of program:C:\Program Files\Java\jdk1.6.0_01\bin>javac A.java

C:\Program Files\Java\jdk1.6.0_01\bin>java A
4
Java Interpreter
We can run Java on most platforms provided a platform must has a Java interpreter.


We can run Java on most platforms provided a platform must has a Java interpreter. That is why Java applications are platform independent. Java interpreter translates the Java bytecode into the code that can be understood by the Operating System. Basically, A Java interpreter is a software that implements the Java virtual machine and runs Java applications. As the Java compiler compiles the source code into the Java bytecode, the same way the Java interpreter translates the Java bytecode into the code that can be understood by the Operating System.

When a Java interpreter is installed on any platform that means it is JVM (Java virtual machine) enabled platform. It (Java Interpreter) performs all of the activities of the Java run-time system. It loads Java class files and interprets the compiled byte-code. You would be glad to know that some web browsers like Netscape and the Internet Explorer are Java enabled. This means that these browsers contain Java interpreter. With the help of this Java interpreter we download the Applets from the Internet or an intranet to run within a web browser. The interpreter also serves as a specialized compiler in an implementation that supports dynamic or "just in time," compilation which turns Java byte-code into native machine instructions.

Throughout Java programming, we'll build both, the standalone Java programs and applets.

Sun's Java interpreter is called java. Lets learn how to start a standalone application with it. Load an initial class and specify it. Some options can also be specified to the interpreter, and any command-line arguments needed for the application as well:

% java [interpreter options] class name [program arguments]

The class should be specified as a fully qualified class name including the class package, if any.
Note : Moreover, we don't include the .class file extension. Here are a few examples:

% java animals.birds.BigBird
% java test

Once the class is loaded, java follows a C-like convention and searches for the class that contains a method called main(). If it finds an appropriate main() method, the interpreter starts the application by executing that method. From there, the application starts additional threads, reference other classes, and create its user interface.

Now, lets see how to go about an Applet. Although Java applet is a compiled Java code, the Java interpreter can't directly run them because they are used as part of a larger applications. For this we use Java Applet Viewer. It is a command line program to run Java applets. It is included in the SDK. It helps you to test an applet before you run it in a browser. We will learn more about it later.


Java Debugger
Java debugger helps in finding and the fixing of bugs in Java language programs.

Java debugger helps in finding and the fixing of bugs in Java language programs. The Java debugger is denoted as jdb. It works like a command-line debugger for Java classes.

jdb session

The way to start the jdb session is to have jdb launch a new JVM (Java virtual machine) with the main class. Then the application of the main class is debugged by substituting the command jdb in command-line. For instance, if the main class of the application is TempClass, the following command is used to debug it:

% jdb TempClass

There is another way to use jdb i.e.to attach jdb to Java VM which is already running.

There are few options which are used to debug a VM with jdb. These are:option purpose
-Xdebug Enables debugging in the VM
-Xrunjdwp:transport=dt_socket,server=y,suspend=n Loads in-process debugging libraries and specifies the kind of connection to be made


The following command will run the TempClass application to which the jdb will connect afterwords.

% java -Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n TempClass

Now the jdb will be attached to the VM in this way: % jdb -attach 8000

You can go through the basic jdb commands that the Java debugger supports.

cont
Ihis command Continues the execution of the debugged application after a breakpoint, exception, or step.

run
Use run command to start the execution after starting jdb, and setting any necessary breakpoints, use run command to start the execution . When jdb launches the debugged application then only this command is available.

print
This command is used to display Java objects and primitive values. The actual value is printed for the variables or fields of primitive types. For objects, a short description is printed.

Few examples of print command are:
print TempClass.myStaticField
print myObj.myInstanceField
print myObj.myMethod()

dump
This command is similar to print command. For objects, it is used to print the current value of each field defined in the object including Static and instance fields.
The dump command supports the same set of expressions as the print command.

Exceptions
If any kind of exception occurs in the program, the VM will print an exception trace and exits. It will only print this exception when there isn't any catch statement in the throwing thread's call stack.
There is another command to be used to stop the debugged applications at other thrown exceptions. The command is catch command. For instance, "catch java.io.FileNotFoundException" or "catch mypackage.BigTroubleException.
Also the ignore command negates the effect of a previous catch command.

help, or ?
The command which helps in displaying the list of recognized commands is the help or ? command.

threads
This command list the threads that are currently running. The name and current status are printed for each thread. The index is also printed that can be used for other commands, for example:
4. (java.lang.Thread)0x1 main running
This example shows that the thread index is 4, the thread is an instance of java.lang.Thread, the thread name is "main", and it is currently running.

thread
This command selects a thread to be the current thread. Some jdb commands are based on the setting of the current thread. The thread index specifies the thread as explained in the threads command above.

where
The command where is used to dump the stack of the current thread. Whereas the command where all is used to dump the stack of all threads in the current thread group. And the where thread index command is used to dump the stack of the specified thread.

Breakpoints
The way to use Breakpoints is to set it in jdb at line numbers or at the first instruction of a method, for example:
stop at TempClass:14 (sets a breakpoint at the first instruction for line 14 of the source file containing TempClass)
stop in TempClass. ( identifies the TempClass constructor)
It is essential to specify the argument types whenever we overload any method in order to select the proper method for a breakpoint. For example, "TempClass.myMethod(int,java.lang.String)", or "TempClass.myMethod()".
We also use the clear command to remove breakpoints using a syntax as in "clear TempClass:20" and the cont command continues execution.

Command Line Options

Use jdb in place of the Java application launcher on the command line, it accepts most of the same options as the java command, which includes -D, -classpath, and -X

Attaches the debugger to previously running VM using the default connection mechanism.-launchAs soon as the jdb start sup,launch option launches the debugged application immediately. We need not to use the run command after using this option.-JoptionIt passes option to the Java virtual machine, where option is one of the options described on the reference page for the java application launcher. For example, -J-Xms48m sets the startup memory to 48 megabytes.Lets tweak an example:public class Y { public static int add(int a, int b) { return a+b; } public static int sub(int a, int b) { return a-b; } public static void main(String args[]) { int a = 10; int b = 20; int c; c = add(a, b); System.out.println(c); c = sub(a, b); System.out.println(c); }}After compiling and running the above program, we will initialize the java debugger and we will use the Stop command to out a breakpoint. After that we will use run command to start the jdb. In the similar way we can use other commands as well.C:\javac>jdb YInitializing jdb ...> stop at Y:6Deferring breakpoint Y:6.It will be set after the class is loaded.> runrun YSet uncaught java.lang.ThrowableSet deferred uncaught java.lang.Throwable>VM Started: Set deferred breakpoint Y:6Breakpoint hit: "thread=main", Y.add(), line=6 bci=06 return a+b;main[1] where[1] Y.add (Y.java:6)[2] Y.main (Y.java:17)main[1] methods Y** methods list **Y ()Y add(int, int)Y sub(int, int)Y main(java.lang.String[])java.lang.Object ()java.lang.Object registerNatives()java.lang.Object getClass()java.lang.Object hashCode()java.lang.Object equals(java.lang.Object)java.lang.Object clone()java.lang.Object toString()java.lang.Object notify()java.lang.Object notifyAll()java.lang.Object wait(long)java.lang.Object wait(long, int)java.lang.Object wait()java.lang.Object finalize()java.lang.Object ()Java Header File GeneratorIn Java programming we need to implement some native methods. To implement these methods Javah generates C header and source files that are used by C programs to reference an Object's instance variables from native source code. In Java programming we need to implement some native methods. You must be wondering about what's native methods.Firstly, The native methods are in pure C code, not C++. The function prototypes are in an object-oriented form of C which are being provided by javah , but they are still not object methods.Secondly, We can call native methods applications only. However due to some security reasons, we cannot call applets from native methods.Thirdly, native methods are platform-specific. This is the most important point to remember, you have to build a dynamically loadable library to link your java application with the native operating system (Windows OS, Machintosh, Linux, Unix ..). For each native platform your application targets, a dynamically loadable library is needed to be shipped.. That means any system-specific code has to be ported along with the java code.On the other hand, native methods are the only way to use any system features not provided by the Java Virtual Machine.To implement these methods Javah generates C header and source files that are used by C programs to reference an Object's instance variables from native source code. The name of the header file and the structure declared within it are derived from the name of the class.By default javah creates a header file for each class listed on the command line and puts the files in the current directory. As stated above the name of the header file is derived from the name of the class. If any class inside the package is passed to javah, the package name gets prepended to both the header file name and the structure name.Following are some options to use :-o outputfileThis option concatenates the resulting header or source files for all the classes listed on the command line into output file.-helpPrint help message for javah usage.-d directoryThis option sets the directory where javah saves the header files or the stub files. Only one of -d or -o may be used.-classpath pathSpecifies the path javah used to look up classes. Overrides the default or the CLASSPATH environment variable if it is set. Directories are separated by semi-colons. Thus the general format for path is:.;For example:.;C:\users\dac\classes;C:\tools\java\classes-stubsCauses javah to generate C declarations from the Java object file.-verboseIndicates verbose output and causes javah to print a message to stdout concerning the status of the generated files.-versionPrints out javah version information.JavaDocThis tool is used to generate API documentation into HTML format from Java source code. Sun Microsystems has provided a computer software tool known as Javadoc. This tool is used to generate API documentation into HTML format from Java source code. It is interesting to know that Javadoc is the industry standard for documenting Java classes.Sun Microsystems has provided a computer software tool known as Javadoc. This tool is used to generate API documentation into HTML format from Java source code. It is interesting to know that Javadoc is the industry standard for documenting Java classes.Javadoc is a program that is already included in JDK. We can use Javadoc to run over the source code to produce documentation of our classes in the HTML files . We have to tag our code with by using some comment formats to use javadoc tag on our source code. For instance Javadoc comments looks like this:NOTE : To start a Javadoc comments use /** to start, and */ to end, and use tags such as @param, @return, and @exception in between to describe the workings of a method.The format is given below to use the Javadoc comments:/*** Summary of the sentence.* information about the* program, class, method or variable* then the comment, using as many lines* as necessary.** zero or more tags to specify any type* of information, such as parameters and return* values for a method*/Start with comment delimiter (/*) followed by another (*). The next line starts with an asterisk and write as many line as you want starting with an asterisk. The last line ends with the delimiter (*/). The first sentence to start with is a "summary sentence" showing the description of the program, class, method or variable. We can write few more lines if required, but not any blank lines. After writting the general description, a sequence of tags follows leaving a blank line.Use different tags to display different situations. The example below shows a Javadoc comment without tags that describes the variable declared immediately below it:/*** The number of employees in a company. This variable must not be* negative or greater than 200.*/public int numEmployees;One interesting thing to know about Javadoc comments is that we can embed HTML tags to format the text. For example:/*** Java declaration*/Lets have a look on Javadoc tags Tag Description@version Shows the version number of a class or method.@author Shows the Developer name@return Documents the return value. This tag should not be used for constructors or methods defined with a void return type.@deprecated Marks a method as deprecated. Some IDEs will issue a compilation warning if the method is called.@see Documents an association to another method or class.@param Defines a method parameter. Required for each parameter.@throws Documents an exception thrown by a method. A synonym for @exception introduced in Javadoc 1.2.@since Documents when a method was added to a class.@exception Documents an exception thrown by a method — also see @throws.private Displays all classes and membersuse It creates class and package usage pagesWindowtitle It shows the window title of the documentHeader It includes for header text of the pageFooter It includes footer text for the page Bottom It includes bottom text for the pagePackage Shows package classes and membersProtected shows protected classes and membersClasspath Helps to find user class filesnoindex doesn't provide the indexnohelp doesn't provide the help linknotree doesn't provide class hierarchyTo document source code developers use certain commenting styles and Javadoc tags. A Java block comment starting with /** will begin a Javadoc comment block This comment block will be included in the HTML. Some tags are provided in the above table which begins with an "@" (at sign).Applet ViewerApplet viewer is a command line program to run Java applets. Applet viewer is a command line program to run Java applets. It is included in the SDK. It helps you to test an applet before you run it in a browser.Applet viewer is a command line program to run Java applets. It is included in the SDK. It helps you to test an applet before you run it in a browser. Before going any further, lets see what an applet is?An applet is a special type of application that's included as a part of an HTML page and can be stored in a web page and run within a web browser. The applet's code gets transferred to the system and then the Java Virtual Machine (JVM) of the browser executes that code and displays the output.. So for running the applet, the browser should be Java enabled. To create an applet, we need to define a class that inherits the Applet.We generally use web browsers to run applets. Its not always mandatory to open a Web browser for running an applet. There is another way as well. The other way to run an applet is through Java applet viewer. This is a tool that acts as a test bed for Java applets. The working of Applet viewer is a bit different from a Web browser, though they are logically same. The Applet viewer runs on the HTML documentation, and uses embedded applet tags. The difference in using the applet viewer and the web browser to run the applet is that the applet viewer only deals with the applet code not the HTML cod i.e. it doesn't display HTML code. So we should test our program in applet viewer and web browser to confirm its working.The applet viewer command connects to the documents or resources designated by urls. It displays each applet referenced by the documents in its own window.The syntax for the applet viewer is:appletviewer Options URLWhere the URL specifies the location of the applet program and the Options argument specifies how to run the Java applet. We can use only one option -debug that starts the applet viewer in the Java debugger. Using this option we can debug an applet.The following program shows how to build an applet and the HTML file for it. Firstly create a class. Then start the applet using init method. After that enter a string as str = "This is my first applet". Use paint method to give the dimensions of the applet. Beneath that is the HTML file which shows how to give the body for applet.Here is the Java File:import java.applet.*;import java.awt.*;public class Myapplet extends Applet{ String str; public void init(){ str = "This is my first applet"; } public void paint(Graphics g){ g.drawString(str, 50,50); }}Here is the HTML File:After building the program, run the applet and the applet viewer as shown below.C:\javac> javac Myapplet.javaC:\javac>appletviewer Myapplet.htm

The Java Applet Viewer

Applet viewer is a command line program to run Java applets. It is included in the SDK. It helps you to test an applet before you run it in a browser. Before going any further, lets see what an applet is?

An applet is a special type of application that's included as a part of an HTML page and can be stored in a web page and run within a web browser. The applet's code gets transferred to the system and then the Java Virtual Machine (JVM) of the browser executes that code and displays the output.. So for running the applet, the browser should be Java enabled. To create an applet, we need to define a class that inherits the Applet.

We generally use web browsers to run applets. Its not always mandatory to open a Web browser for running an applet. There is another way as well. The other way to run an applet is through Java applet viewer. This is a tool that acts as a test bed for Java applets. The working of Applet viewer is a bit different from a Web browser, though they are logically same. The Applet viewer runs on the HTML documentation, and uses embedded applet tags. The difference in using the applet viewer and the web browser to run the applet is that the applet viewer only deals with the applet code not the HTML cod i.e. it doesn't display HTML code. So we should test our program in applet viewer and web browser to confirm its working.

The applet viewer command connects to the documents or resources designated by urls. It displays each applet referenced by the documents in its own window.

The syntax for the applet viewer is:

appletviewer Options URL

Where the URL specifies the location of the applet program and the Options argument specifies how to run the Java applet. We can use only one option -debug that starts the applet viewer in the Java debugger. Using this option we can debug an applet.

The following program shows how to build an applet and the HTML file for it. Firstly create a class. Then start the applet using init method. After that enter a string as str = "This is my first applet". Use paint method to give the dimensions of the applet. Beneath that is the HTML file which shows how to give the body for applet.

Here is the Java File:import java.applet.*;
import java.awt.*;
public class Myapplet extends Applet{
String str;
public void init(){
str = "This is my first applet";
}
public void paint(Graphics g){
g.drawString(str, 50,50);
}
}


Here is the HTML File:







After building the program, run the applet and the applet viewer as shown below.C:\javac> javac Myapplet.java

C:\javac>appletviewer Myapplet.html


When we run the applet viewer it will display the window as shown below.