Monday, February 27, 2012

Struts HTML Tag

Struts HTML Tag

In this example you will learn how to use Struts HTML Tags. In order to use the Struts HTML Tags you need to include the following taglib directive in the jsp page.

< %@taglib uri="/WEB-INF/struts-html.tld" prefix="html" % >

All the Struts HTML tags should be nested within the body of the tag. We will create a simple feedback form to see how the different Struts HTML Tags can be used. The feedback.jsp contains the following code.

< %@taglib uri="/WEB-INF/struts-html.tld" prefix="html" % >
< html>
< head>
< meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
< title >Feedback Form< /title >
< /head >
< body >
< b >Feedback Form< /b >
< hr >
< html:form action="/feedbackAction" >
< table >
< tr >
< td >
Name :
< /td >
< td >
< html:text name="feedbackForm" property="name" / >
< /td >
< /tr >
< tr >
< td >
Sex :
< /td >
< td >
< html:radio name="feedbackForm" property="sex" value="M" >
M < /html:radio >
< html:radio name="feedbackForm" property="sex" value="F" >
F < /html:radio >
< /td >
< /tr >
< tr >
< td >
Comments :
< /td >
< td >
< html:textarea cols="20" rows="5" name="feedbackForm"
property="comments" / >
< /td >
< /tr >
< tr >
< td >
< html:submit / >
< /td >
< td >
< html:reset / >
< /td >
< /tr >
< /table >
< /html:form >
< /body >
< /html >

The name attribute of the HTML tag contains the Form Bean name. The property attribute of the HTML Tag contains the corresponding Form property.

Once the feedback is submitted by the user, the user will be forwarded to the success page. Here the feedback submitted by the user will be displayed. We use Struts Bean Tag do to this. We use Struts Logic Equal Tag to display Male if the user has selected M for sex and Female if the user has selected F for sex. In order to use the Struts Bean and Logic Tag you need to include the following taglib directives in the jsp page.

< %@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" % >
< %@taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" % >

The success.jsp page contains the following code.

< %@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" % >
< %@taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" % >
< html>
< head>
< meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
< title >Feedback Form< /title >
< /head >
< body >
< b >Feedback Successfully Submitted.< /b >< br >
You have submitted the following feedback.
< table >
< tr >
< td >
Name :
< /td >
< td >
< bean:write name="feedbackForm" property="name" / >
< /td >
< /tr >
< tr >
< td >
Sex :
< /td >
< td >
< logic:equal name="feedbackForm" property="sex" value="M" > Male < /logic:equal >
< logic:equal name="feedbackForm" property="sex" value="F" > Female < /logic:equal >
< /td >
< /tr >
< tr >
< td >
Comments :
< /td >
< td >
< bean:write name="feedbackForm" property="comments" / >
< /td >
< /tr >
< /table >
< /body >
< /html >

On executing the example the following page will be dispalyed to the user.

On submitting the feedback the following page will be dispalyed to the user.

Struts MVC Architecture

Struts 1 > MVC Architecture
Struts MVC Architecture

The model contains the business logic and interact with the persistance storage to store, retrive and manipulate data.

The view is responsible for dispalying the results back to the user. In Struts the view layer is implemented using JSP.

The controller handles all the request from the user and selects the appropriate view to return. In Sruts the controller's job is done by the ActionServlet.


The following events happen when the Client browser issues an HTTP request.

The ActionServlet receives the request.
The struts-config.xml file contains the details regarding the Actions, ActionForms, ActionMappings and ActionForwards.
During the startup the ActionServelet reads the struts-config.xml file and creates a database of configuration objects. Later while processing the request the ActionServlet makes decision by refering to this object.

When the ActionServlet receives the request it does the following tasks.

Bundles all the request values into a JavaBean class which extends Struts ActionForm class.
Decides which action class to invoke to process the request.
Validate the data entered by the user.
The action class process the request with the help of the model component. The model interacts with the database and process the request.
After completing the request processing the Action class returns an ActionForward to the controller.
Based on the ActionForward the controller will invoke the appropriate view.
The HTTP response is rendered back to the user by the view component.

Wednesday, February 22, 2012

Struts part 2

Struts part 2
Struts view components
Custom Tags
•html
•Logic
•bean
•nested
Example code using the struts html tag
<%@ taglib uri=“../struts-html.tld” prefix=“html”%>
< html >

< html:form action=“login.do” >
User: < html:text property=“userId”/ >
Password: < html:password property=“password”/ >
< html:submit value=“Submit”/ >
< /html:form>

< /html >
ActionForm • Used to pass client data between the user and business layer.

• Framework collects the input(parameters) from request and populates the action forms using form beans.

Model – View – Controller

Model-view-controller (MVC) is a design pattern used to separate data (model) and user interface (view), so that changes to the user interface do not impact the data handling and vice versa.
Model
• The domain-specific representation of the information on which the application operates. i.e the data and the business logic.

View
• Renders the model into a form suitable for interaction, typically a user interface element. HTML pages in case of web applications

Controller
• Processes and responds to user actions (request in web apps), and may invoke changes on the model.
• The model has no direct knowledge of the view.

Configuring Struts
•struts.jar in /WEB-INF/lib/
< web-app >
< servlet >
< servlet-name >action< /servlet-name >
< servlet-class >org.apache.struts.action.ActionServlet< /servlet-class >
< init-param>
< param-name>config< /param-name >< param-value >/WEB-INF/struts-config.xml< /param-value >< /init-param >
< /servlet >
< servlet-mapping >
< servlet-name >action< /servlet-name >
< url-pattern >*.do< /url-pattern >
< /servlet-mapping >
< taglib >
< !- - taglibs used in the applications – >
< /taglib >
< /web-app >

Struts controller components

ActionServlet
•Extends HttpServlet
•Configured in web.xml, all requests reach the ActionServlet
•Instantiates and passes the request to the RequestProcessor
RequestProcessor
•Delegates the handling of the request to a helper class(Action Class) based on the struts configuration file.
Struts Action Classes
•Acts as a bridge between client side user action and business operation
•Can perform other functions like authorization, logging and session validation before invoking the business operation.
•We usually extend the Action class and override the execute method

Class LoginAction extends Action{
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){
//take request parameters from the form and process them
// return the next view
return mapping.findForward(“nameOfNextView”)
}
}
Struts-config.xml
< struts-config >

< action path=“\login” type=”com.sample.struts.action.LoginAction” scope=”request” name=”loginForm” validate=”true” input=”/login.jsp” >
< forward name=”success” path=“/homepage.jsp”/ >
< forward name=”failure” path=”/login.jsp”/ >
< exception key=”error.invalidlogin” path=”/login.jsp” scope=”request” type=”come.sample.struts.exception.InvalidLoginException”/ >
< /action >

< struts-config >
Dispatch Action
•Allows multiple operations normally scattered across multiple action classes to a single class.
• Related functionality can be kept in a DispatchAction subclass
< action path=“\login” type=”com.sample.struts.action.AccountAction” scope=”request” parameter=”method” name=”loginForm” >
< forward name=”success” path=“/homepage.jsp”/ >
< forward name=”failure” path=”/login.jsp”/ >
< exception key=”error.invalidlogin” path=”/login.jsp” scope=”request” type=”come.sample.struts.exception.InvalidLoginException”/ >
< /action >
class AccountAction extends DispatchAction{
public ActionForward viewAccount(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){
//take request parameters from the form and process them
// return the next view
return mapping.findForward(“nameOfNextView”)
}
}

Struts model components

Does not directly provide components for model since this is a web framework.

The following are the commonly used models.

•Data Transfer objects
•EJBs
•Business Object.
Struts view components
The components user for view in Struts are
•HTML
•Data Transfer Objects
•Struts Action Forms
•JSP
•Custom Tags
•Resource Bundles

What is Struts

What is Struts

Struts Frame work is the implementation of Model-View-Controller (MVC) design pattern for the JSP. Struts is maintained as a part of Apache Jakarta project and is open source. Struts Framework is suited for the application of any size. Latest version of struts can be downloaded from http://jakarta.apache.org/. We are using jakarta-struts-1.1 and jakarta-tomcat-5.0.4 for this tutorial.

The framework provides three key components:

A “request” handler provided by the application developer that is mapped to a standard URI.
A “response” handler that transfers control to another resource which completes the response.
A tag library that helps developers create interactive form-based applications with server pages.

The framework’s architecture and tags are buzzword compliant. Struts works well with conventional REST applications and with nouveau technologies like SOAP and AJAX.
Downloading and Configuring Struts

Download the Struts zip file.
Start at http://jakarta.apache.org/site/binindex.cgi, or follow the link from http://jakarta.apache.org/struts/. I’m using Struts 1.1 in this tutorial.
Unzip into a directory of your choice.
For example, unzip into C:\jakarta-struts-1.1. Throughout the rest of this tutorial, I’ll refer to this location as struts_install_dir.
Update your CLASSPATH.
Add struts_install_dir/lib/struts.jar to the CLASSPATH used by your compiler or IDE (not your server). Here are three possible ways of setting it:

Set it in your autoexec.bat file. E.g., on Windows if you unzipped into C:\jakarta-struts-1.1, you would add the following to C:\autoexec.bat:
set CLASSPATH=C:\jakarta-struts-1.1\lib\struts.jar;%CLASSPATH%
On Unix/Linux, use your .cshrc, .bashrc, or .profile instead.
Set it using the system settings. On WinXP, go to the Start menu and select Control Panel, then System, then the Advanced tab, then the Environment Variables button. On Win2K/WinNT, go to the Start menu and select Settings, then Control Panel, then System, then Environment. Either way, enter the CLASSPATH value from the previous bullet.
Set it in your editor or IDE. Most IDEs have a way of specifying the JAR files needed to compile projects. Or, you could make a small .bat file (Windows) or shell script (Unix/Linux) that supplies the struts.jar file as the argument to -classpath for javac.
Install an XML parser.
If you have JDK 1.4 or Apache Tomcat, this step is not necessary, since they already come with an XML parser. But, if you use JDK 1.2 or 1.3 with another server, you might need to obtain the XML parsing libraries. Here are two good sources:

http://xml.apache.org/
http://java.sun.com/xml/
Testing Struts
Install struts-blank.war.
Install the Web application from struts_install_dir/webapps/struts-blank.war on your server. For example, with Apache Tomcat, copy struts_install_dir/webapps/struts-blank.war to tomcat_install_dir/webapps/.
Start or restart the server.
Most servers only recognize new Web apps when the server is started.
Access http://localhost/struts-blank/.
This URL assumes you are running the server on your desktop and are using port 80. In general, access http://hostname:port/struts-blank/. You should see something like the following.

Setting Up Struts Applications

To make your own Struts application, you need to create a Web application that has the appropriate JAR files, TLD files, and web.xml entries. You almost always do this by starting with the struts-blank application and modifying it. You have three options for doing this:
Accessing Struts Documentation

You probably already have bookmarked the APIs for standard Java, servlets, and JSP. But you will also want to frequently refer to the Apache Struts documentation. You can do this two ways:
Adding Struts to an Existing Web Application

By far the easiest way to develop a Struts application is to start with struts-blank, rename it, and work from there. If that approach is an option for you, do it that way and skip this section. However, if you already have an existing Web application and want to add Struts capabilities to it, starting with struts-blank won’t work. Adding Struts capabilities to existing Web apps is a huge pain in the neck, and will proably require several attempts to get it right. Here is a quick summary:

Copy JAR files from struts-blank/WEB-INF/lib to your_web_app/WEB-INF/lib.
Copy TLD files from struts-blank/WEB-INF to your_web_app/WEB-INF.
Copy struts-config.xml from struts-blank/WEB-INF to your_web_app/WEB-INF.
Copy the application properties file from struts-blank/WEB-INF/classes/resources to your_web_app/WEB-INF/classes/resources.
If you plan on using the automatic validator (see Section 5, Validating User Input), copy validation.xml and validator-rules.xml from struts-blank/WEB-INF to your_web_app/WEB-INF.
If you plan on using Tiles (see Section 6, Composing Pages with Tiles), copy struts-tiles.xml from struts-blank/WEB-INF to your_web_app/WEB-INF.
Copy declarations out of struts-blank/WEB-INF/web.xml into your_web_app/WEB-INF/web.xml. Most importantly, copy the servlet and servlet-mapping entries that map *.do to org.apache.struts.action.ActionServlet. Be sure you keep the entries in the same locations: the order of elements in web.xml matters.

Struts Architecture

Struts Architecture

Struts is an open source framework used for developing J2EE web applications using Model View Controller (MVC) design pattern. It uses and extends the Java Servlet API to encourage developers to adopt an MVC architecture. Struts framework provides three key components:

A request handler provided by the application developer that is used to mapped to a particular URI.

A response handler which is used to transfer the control to another resource which will be responsible for completing the response.

A tag library which helps developers to create the interactive form based applications with server pages.

Struts provides you the basic infrastructure infrastructure for implementing MVC allowing the developers to concentrate on the business logic.

MVC Architecture

The main aim of the MVC architecture is to separate the business logic and application data from the presentation data to the user.

Here are the reasons why we should use the MVC design pattern.

They are resuable : When the problems recurs, there is no need to invent a new solution, we just have to follow the pattern and adapt it as necessary.

They are expressive: By using the MVC design pattern our application becomes more expressive.

1). Model: The model object knows about all the data that need to be displayed. It is model who is aware about all the operations that can be applied to transform that object. It only represents the data of an application. The model represents enterprise data and the business rules that govern access to and updates of this data. Model is not aware about the presentation data and how that data will be displayed to the browser.

2). View : The view represents the presentation of the application. The view object refers to the model. It uses the query methods of the model to obtain the contents and renders it. The view is not dependent on the application logic. It remains same if there is any modification in the business logic. In other words, we can say that it is the responsibility of the of the view’s to maintain the consistency in its presentation when the model changes.

3). Controller: Whenever the user sends a request for something then it always go through the controller. The controller is responsible for intercepting the requests from view and passes it to the model for the appropriate action. After the action has been taken on the data, the controller is responsible for directing the appropriate view to the user. In GUIs, the views and the controllers often work very closely together.

Overview of the Struts Framework

The Struts framework is composed of approximately 300 classes and interfaces which are organized in about 12 top level packages. Along with the utility and helper classes framework also provides the classes and interfaces for working with controller and presentation by the help of the custom tag libraries. It is entirely on to us which model we want to choose. The view of the Struts architecture is given below:

The Struts Controller Components:

Whenever a user request for something, then the request is handled by the Struts Action Servlet. When the ActionServlet receives the request, it intercepts the URL and based on the Struts Configuration files, it gives the handling of the request to the Action class. Action class is a part of the controller and is responsible for communicating with the model layer.

The Struts View Components:

The view components are responsible for presenting information to the users and accepting the input from them. They are responsible for displaying the information provided by the model components. Mostly we use the Java Server Pages (JSP) for the view presentation. To extend the capability of the view we can use the Custom tags, java script etc.

The Struts model component:

The model components provides a model of the business logic behind a Struts program. It provides interfaces to databases or back- ends systems. Model components are generally a java class. There is not any such defined format for a Model component, so it is possible for us to reuse Java code which are written for other projects. We should choose the model according to our client requirement.

Struts part 3

Struts part 3

Custom Tags

• html
• Logic
• bean
• nested
Example code using the struts html tag

< %@ taglib uri=“../struts-html.tld” prefix=“html”% >

< html >…

< html:form action=“login.do” >

User: < html:text property=“userId”/ >

Password: < html:password property=“password”/ >

< html:submit value=“Submit”/ >

< /html:form>

< /html >
Struts Configuration File
< struts-config >
… < form-beans >

< form-bean name=”loginForm” type=”com.sample.struts.form.LoginForm”/ >
… < /form-beans > …

< /struts-config >

DynaActionForms

< struts-config >

.< form-beans >

< form-bean name=”loginForm”

type=”org.apache.struts.action.DynaActionForm” >

< form-property name=”userId” type=”java.lang.String”/ >

< form-property name=”password” type=”java.lang.String”/ >

< /form-bean >

< /form-beans >

…< /struts-config >

Login Page

< html:form action=“login.do” >
User: < html:text property=“userId”/ >
Password: < html:password property=“password”/ >
< html:submit value=“Submit”/ >
< /html:form >

ActionForm
public LoginForm extends Action Form{
private String userId; //getter and setter methods for these.
private String password;
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request){
ActionErrors errors = new ActionErrors();
if(userId == null || “”.equals(userId)){
ActionError error = new ActionError(“error.login.userRequired”);
errors.add(error);
} //other validations
return errors;
}
}

Struts-config.xml
< struts-config >
< form-beans >
< form-bean name=”loginForm” type=”com.sample.struts.form.LoginForm”/>
< /form-beans >

< global-exceptions >
< exception key=“error.nodatabase” path=“/error.jsp” type=“com.sample.struts.DatabaseException”/ >
< /global-exceptions >
< global-forwards >



< action-mappings >
< action path=“\login” type=”com.sample.struts.action.LoginAction” scope=”request” name=”loginForm” validate=”true” input=”/login.jsp” >
< forward name=”success” path=“/homepage.jsp”/ >
< forward name=”failure” path=”/login.jsp”/ >
< exception key=”error.invalidlogin” path=”/login.jsp” scope=”request” type=”come.sample.struts.exception.InvalidLoginException”/ >
< /action >
< /action-mappings >

< message-resources name=“application”/ >
< /struts-config >

Action Class

Class LoginAction extends Action{
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){
LoginForm loginForm = ( LoginForm) form;
String userId = loginForm.getUserId
String password = loginForm.getPassword;
if(authenticate(userId, password){
return mapping.findForward(“success”);
}
return mapping.findForward(“failure”)
}
}
More in Struts

Struts tiles
Advanced templating framework, that separates content from the layout

Struts validator framework
Declaratively configure validation routines without having to program validation logic

Multiple module support
Separate configuration files for different modules, allows for better organization of the components in the web application.

Advantages

-Centralized file based configuration

-Form beans automatically populated from request parameters, validation possible
-Struts custom tags
-Supports tiles, validator framework and internationalization(i18n).
-Consistent use of MVC

Struts1

Struts – part 1
Struts is a widely used open framework for developing Jave EE web applications
•Combines Java Servlets, JSP’s, custom tags and manages resources into a reusable framework
•Based on the Model-View-Controller Design pattern.
•Originally created by Craig McClanahan and donated to the Apache Foundation

In this session -we’ll look on

Model-View-Controller (MVC) Architecture
•How struts implements MVC architecture
•Discuss different components of struts
•A Sample Struts Application
•Advantage of using Struts

Model – View – Controller

Model-view-controller (MVC) is a design pattern used to separate data (model) and user interface (view), so that changes to the user interface do not impact the data handling and vice versa.
Model
• The domain-specific representation of the information on which the application operates. i.e the data and the business logic.

View
• Renders the model into a form suitable for interaction, typically a user interface element. HTML pages in case of web applications

Controller
• Processes and responds to user actions (request in web apps), and may invoke changes on the model.
• The model has no direct knowledge of the view.

Configuring Struts

•struts.jar in /WEB-INF/lib/
< web-app >
< servlet >
< servlet-name >action< /servlet-name >
< servlet-class >org.apache.struts.action.ActionServlet< /servlet-class >
< init-param >
< param-name config< /param-name >
< param-value > /WEB-INF/struts-config.xml< /param-value >
< /init-param >
< /servlet >
< servlet-mapping >
< servlet-name >action< /servlet-name >
< url-pattern >*.do< /url-pattern >
< /servlet-mapping >
< taglib>
< !- - taglibs used in the applications – >
< /taglib >
< /web-app >

Struts controller components

ActionServlet
•Extends HttpServlet
•Configured in web.xml, all requests reach the ActionServlet
•Instantiates and passes the request to the RequestProcessor

RequestProcessor
•Delegates the handling of the request to a helper class(Action Class) based on the struts configuration file.

Struts Action Classes
•Acts as a bridge between client side user action and business operation
•Can perform other functions like authorization, logging and session validation before invoking the business operation.
•We usually extend the Action class and override the execute method

Class LoginAction extends Action{
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){
//take request parameters from the form and process them
// return the next view
return mapping.findForward(“nameOfNextView”)
}
}
Struts-config.xml
< struts-config >

< action path=“\login” type=”com.sample.struts.action.LoginAction” scope=”request” name=”loginForm” validate=”true” input=”/login.jsp” >
< forward name=”success” path=“/homepage.jsp”/ >
< forward name=”failure” path=”/login.jsp”/ >
< exception key=”error.invalidlogin” path=”/login.jsp” scope=”request” type=”come.sample.struts.exception.InvalidLoginException”/ >
< /action >

< struts-config >
Dispatch Action
•Allows multiple operations normally scattered across multiple action classes to a single class.
• Related functionality can be kept in a DispatchAction subclass
< action path=“\login” type=”com.sample.struts.action.AccountAction” scope=”request” parameter=”method” name=”loginForm” >
< forward name=”success” path=“/homepage.jsp”/ >
< forward name=”failure” path=”/login.jsp”/ >
< exception key=”error.invalidlogin” path=”/login.jsp” scope=”request” type=”come.sample.struts.exception.InvalidLoginException”/ >
< /action>
class AccountAction extends DispatchAction{
public ActionForward viewAccount(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){
//take request parameters from the form and process them
// return the next view
return mapping.findForward(“nameOfNextView”)
}
}

Struts model components

Does not directly provide components for model since this is a web framework.

The following are the commonly used models.

•Data Transfer objects

•EJBs

•Business Object.

Struts view components

The components user for view in Struts are

•HTML

•Data Transfer Objects

•Struts Action Forms

•JSP

•Custom Tags

•Resource Bundles

Monday, February 20, 2012

JSTL

In the first part of this tutorial on JSTL, the author gives a brief introduction to JSTL and shows why and how it evolved .
As J2EE programmers, we are familiar with Servlets , JSP and JavaBeans. Any JSP page should encapsulate the business logic in a bean and invoke it by using tag. Till recently, a combination of Servlets, JSP and beans was the standard practice. But, the JCP released an API for enabling programmers to create custom tags and use them in their JSP pages. The difference between javabean and java custom tags was that, though both made use of java classes, tags can be used by non-programmers also without knowledge of Java programming, just as they would use html tags.( From a programmer's perspective,however, a much more important distinction is that tags are specific to the page in which they are created while javabeans are general. )
{{{ Back in 1998, a Web-Server Technology , known as ColdFusion , created by Allaire of Allaire Corporation, was very much in demand!. It was a purely tag-based language, using which page-authors can turn into programmers overnight. The tags were so powerful and simple to use! There is a separate lesson on using ColdFusion for typical web-based database operations, elsewhere in this edition, just to indicate the source of inspiration of the tag library idea, of the JSTL. To this day, ColdFusion is unbeatable, in its power,speed, ease of use and productivity. However, among the various web-server technologies ( namely
ASP, Servlets, JSP,Perl,PHP , ColdFusion &
ASP.net), CF is the only technology that is not free!And perhaps for this reason, it is no longer popular in Indian environment, though it is said to be very much in vogue still, in US!
MacroMedia of 'Flash fame' purchased ColdFusion .There was even a tutorial on MacroMedia ColdFusion Exprsess in DeveloperIQ., a few months back.It is interesting to make a comparison of the CF tags approach and the JSTL approach., especially , in DataBase operations.Readers are requested to read the lesson on ColdFusion,in this edition, after covering sql tags in JSTL , in the fourth part of this tutorial..}}}
To resume,the release of the TagLibrary API, triggered a lot of activity and hundreds of tags were introduced by the java community, some of them 'open' and a few 'proprietary'. This led to a lot of confusion in code maintenance, because knowledge of Java was no longer sufficient to understand and interpret a given jsp page using non-standard tags .The JCP had unwittingly introduced elements of confusion by the JSP-Custom-Tag specification.
To correct this problem, Sun and JCP, initiated the JSP-Standard Tag Library (JSTL) project. Though there are a number of popular and powerful tag-libraries, it is always better for j2ee coders to adopt the JCP standard because, it is likely to be merged into the core specification of Java langauage itself , in future. (That yardstick may be valid for all creations, in Java world. Splintering of the Java platform due to' hyper-active creativity' without the corresponding discipline to get it through a standards body ,is the greatest threat, looming large in the Java-horizon.
Too frequent revisions and additions, that too without caring for backward compatibility,are not conducive to programmer productivity and the net result is that programmers spend ,in learning new twists in grammar, their precious time which should have been spent more usefully in applying that grammar in solving business-logic problems and acquiring proficiency in the chosen application-domain. While, tag library is sometimes very elegant and simple to use, it defeats the very purpose if the tags are not standard tags and if there is proliferation of non-standard tags.It is for this reason that JSTL merits our serious study and adoption.
JSTL is a quite recent development. It was only in 2003, that the official version 1.1 was released and now incorporated into JSP-2.
According to the latest position, the JCP is suggesting that a JSP page should be completely free from any trace of Java code! So, programmers who were writing their JSP using Javabeans and scriptlets , may not be able to carry on in their old style as, to prevent programmers from introducing scripting sections in their pages, there is a provision for turning off scriptlets altogether from a jsp page. If that happens ,all our knowledge of Java coding will be of little use in creating a jsp page, though such knowledge may be useful in creating beans and other types of java programs.
It is thus very important for J2EE students, to understand the trend and get to know the techniques, advantages and limitations of tag libraries...In a way, a study of JSTL is almost synonymous with a study of the latest version of JSP (ie) JSP2.0 .
---------------------------------------
Without an introductory demo for each of these types, it may be difficult to appreciate the significance of the above lines. So we will now give simplest illustration.
==============================================
[It is presumed that readers are conversant with basic Servlets & JSP techniques and executing them in Tomcat environment. In case of any difficulty, they can refer to back issues of this magazine ( from Oct-2003 onwards) and gain access to a number of lessons for illustrations.]
Servlets are full-fledged java-classes and so are very powerful. But, when we want to create a dynamicalay-generated web-page using servlets, it becomes difficult and clumsy.Let us consider a very simple example.
The user fills up text in html form with his name and submits the form,to the servlet. The servlet reads the data , appends a greeting and sends it back to the user.
-----------------------------------------------
We begin with a simple html form;
// greeting.htm
=============

action= 'http://localhost:8080/servlet/greeting'>





-----------------------------------------------------------------------------
(relevant section of greeting.java servlet)
// greeting.java ( code-snippet only)
public void doPost(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException,IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
//-------------------------------
String s = req.getParameter("text1");
out.println("");
out.println("we welcome"+",
");
out.println (s);
out.println(" ");
}
-----------------------------------------------
It will be noticed that we have to write so many 'out.println' statements. This makes the page unreadable.( If String-buffer is used , we can do it with just a single out.println , but forming the correct string may pose difficulties).
It is to solve this problem that JSP was developed five years back(1999).While a servlet interposes HTML in java code, JSP interposes java-code in HTML, as some authors correctly observe..( in this case, we have to modify the action field in html form, so that it refers to the following greeting1.jsp).Student readers will know about 'delimiters' ( <%).in ASP.
This is the same as in JSP. Only the syntax is slightly different.In JSP parlance, the code within delimiters is known as 'scriptlet'.( see greeting1.jsp)
-----------------------------------------------
// greeting1.jsp


<%
String s = request.getParameter("text1");
out.println("we welcome"+
);
out.println(s);
%>


-----------------------------------------------
Some coders prefer to use expressions.
What is an 'expression'? It is a method of sustituting request-time values in html page. ( see greeting2.jsp). Carefully note that there is no semi-colon after ("text1").
----------------------------------------------- // greeting2.jsp


we welcome

<%= request.getParameter("text1") %>


-----------------------------------------------
The third variant is to use a javabean to encapsulate the business-logic. We develop a jsp-bean as follows:
------------------------------------------
// greeter.java
//==============
package ourbeans;
public class greeter {
public greeter() { }
public String greetme(String s) {
return "we welcome..."+s;
}
}
-------------------------------------------
This source file is compiled and the class-file is copied to :
'e:\tomcat5\webapps\root\WEB-INF\classes\ourbeans'

(Carefully note that WEB-INF folder name should be in capital letters).
( Anytime, a new class is placed in Tomcat, we should remember to restart the server).
We can now write our JSP code as follows:
------------------------------------------------
// greeting3.jsp



<%
String s = request.getParameter ("text1");
String r = bean1.greeteme(s);
out.println(r);
%>


----------------------------------------------
We are now entering JSTL zone.
How exactly we should proceed to instal JSTL, we will take up shortly. For the moment, we are just getting familiar with the required syntax. We begin with taglib directive.
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
The directive says that we are using 'core' tags and the prefix will be 'c'. If we want to assign the value 'sam' to a variable 'a' and then print it, the JSTL code will be


-----------------------------------
The Dollar sign & brace will be familiar ground for Perl programmers. In JSTL & JSP-2, it is known as EL ( Expression Language).
==============================================
To consider another example, In servlet & jsp, we write:
String s = request.getParameter("text1");
to collect the input from the user.
The same job is done in JSTL by:

==================================
With these brief hints, it should not be difficult to understand the
following JSP page written by using JSTL core-tags.
-----------------------------------------------
// greeting4.jsp ( uses JSTL)
===========
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>



We welcome




-----------------------------------------------
In the previous examples, there was java code in a few lines atleast. But, in the JSTL example, we find that there are only tags and no java scriptlets. This is the avowed objective of the JSTL initiative,
under the auspices of Java Community Project! Why? This enables , clean separation of Page author's role and Logic programmers' role. Thus maintenance becomes easy.
===============================================
There are five groups under which the JSTL tags have been organized.
They are as follows:
1) core
2) xml
3) sql
4) formatting
5) functions.
----------------------------------------------- The most difficult part is to set up Tomcat so that it executes JSTL. There are some basic requirements, before we can experiment and study the use of JSTL.All that we have studied in using Tomcat for servlets and JSP may not be sufficient to learn JSTL, because, jstl library is not built into Tomcat5 even, as yet.
Without hands-on experimention, JSTL could be confusing and strange,because of the fact that it is very recent . But in coming months, support will be built into Tomcat and we won't have to worry about installing the JSTL libraries inside Tomcat. But, as it is, we have to learn how to set up the necessary development environment..
So , how do we go about , placing the JSTL libraries in tomcat?
------------------------------------------------ The best solution is to get JWSDP1.3.
This is Java Web Service Development' Pack.
( Carefully note the version , however!).
It is good to start with this because, it contains a lot of valuable software , including the latest and greatest from JCP, (ie) JSF
(Java Server Faces).... which may soon replace Struts.
We unzip the jwsdp1.3 and install it in C: drive. There are a number of folders like JAXP, JAXR, JAXB,JAX-RPC, JSF, JSTL etc. in the JWSDP pack.
For the present, we are interested in JSTL folder only. If we expand the JSTL folder, we find four sub folders :
a) docs
b) lib
c) samples
d) tld ( tag library descriptors)
When we look into the 'lib' folder, we find two jar files:
a) standard.jar
b) jstl.jar
We should copy these two jar files into :
'e:\tomcat5\webapps\root\WEB-INF\lib'
-----------------------------------------------
( Remember to restart the Tomcat server). That is all that is required to use JSTL. !
The included taglibrary descriptors do not have to be placed in the WEB-INF folder.These files are already included in the /META-INF folder of the jstl.jar and so will be automatically loaded by Tomcat, when it is restarted.
***********************************************
( we are using tomcat5 & jdk1.4.2)
( the results are not ensured for other environments.).( however, we adopted the same method in Tomcat4.1 with jdk1.41 and got correct functioning.)
===============================================
The JSTL folder contains a sub-folder named 'tld'. There will be a number of tld files there such as
c.tld, ( core)
x.tld, (xml)
fmt.tld, (format)
sql.tld & (sql)
fn.tld. (functions)
------------------------------
Some authors say that we should copy these tld files to ..
..:\tomcat5\webapps\root\WEB-INF folder.
A few others , say that there is automatic detection and so it is not necessary. We chose not to copy the tld files into
e:\tomcat5\webapps\root\WEB-INF folder !
We found that the programs works well. No problem!
When we study the web.xml file in e:\tomcat\webapps\root\WEB-INF folder, we find that it follows DTD and not Schema.
( DTD stands for Document -Type- Definition).
( Schema serves the same purpose but is in XML format and is more powerful). ( The default is DTD ).
This point is very important. The default allows us to use EL,(Expression Language) but by using If we modify the DTD into the prescribed J2EE schema , we can directly print as ${s}. This requires very careful handling and we take it up later.

Creating an SMS Composer Application in NetBeans IDE 6.8 tutorial.

To  this tutorial, you need the software and resources listed below.
Software or Resource Version Required
NetBeans IDE with Java ME Version 6.9 and later
Java Development Kit (JDK) Version 6 and version 7

Installing and Running the Sample Application

Before we begin, you might want to see final result of the tutorial.
Take the following steps to install the SMSComposerExample application:
  1. Download SMSComposerExample.zip.
  2. Unzip the file.
  3. In the IDE, choose File > Open Project and browse to the folder that contains the unzipped files with the SMSComposerExample project.
  4. Click Open Project.
    The Projects window should look like the following:
    Projects window with SMS Composer example opened
  5. In the Projects window, right-click the project node and choose Run Project (or press F6).
    As the application runs, an emulator window opens and displays the application running in the default device emulator.
  6. In the Emulator window, click the button underneath "Launch". The emulator displays a Splash Screen component then SMS Composer, as shown:
    WTK 2.5 emulator displaying the sampel SMS Composer application
  • Move the cursor up and down to navigate through available options like Phone Number or Message.
  • Click the central button to enable the selected text field for editing.
  • Click the button underneath "Send" to send the message.
  • Click the button underneath "Exit" to close the application.


Creating an Application with the SMS Composer Custom Component

Now that you have seen the SMS Composer component in action, let's go back to the beginning and create this application. To create the application, do the following:
  1. Create the SMSComposerExample project
  2. Add Packages and a Visual MIDlet to the Project
  3. Add Components to the Project
  4. Add Commands to the Project
  5. Connect the Components to Create an Application Flow
  6. Modify Task for Wait Screen
  7. Run the Project

Creating the SMSComposerExample Project

  1. Choose File > New Project (Ctrl-Shift-N). Under Categories, select JavaME. Under Projects, select Mobile Application and click Next.
  2. Enter SMSComposerExample in the Project Name field. Change the Project Location to a directory on your system. From now on let's refer to this directory as $PROJECTHOME.
  3. Uncheck the Create Hello MIDlet checkbox. Click Next.
  4. Leave the Sun Java Wireless Toolkit as the selected Emulator Platform. Click Next.
  5. Click Finish.
  6. Note: The project folder contains all of your sources and project metadata, such as the project Ant script.

Adding Packages and a Visual MIDlet to the Project

  1. Choose the SMSComposerExample project in the Project Window, then choose File > New File (Ctrl-N). Under Categories, select Java. Under File Types, select Java Package. Click Next.
  2. Enter smscomposerexample in the Package Name field. Click Finish.
  3. Choose the smscomposerexample package in the Project window, then choose File > New File (Ctrl-N). Under Categories, select MIDP. Under File Types, select Visual MIDlet. Click Next.
  4. Enter SMSComposerExample into MIDlet Name and MIDP Class Name fields. Click Finish.
    The application displays in the Flow Design window of the Visual Mobile Designer.
  5. SMSComposerExample in the Visual Mobile Designer

Adding Components to the Project

  1. In the Flow Designer window, drag and drop the following components from the Component Palette:
    • Splash Screen
    • SMS Composer
    • Wait Screen
    • Alert (x2)
  2. Click on splashScreen and, in the Properties Window, change value of property Text from null to the SMS Composer Example and press Enter.
  3. Click on alert and, in the Properties Window, change value of property Title from alert to the alertSent, the same way change alert1 Title property from alert1 to the alertError.
  4. Click on alert and, in the Properties Window, change value of property String to the Message Sent, the same way change property String in the component alertError to the Error.
  5. Click on smsComposer and, in the Properties Window, uncheck the Automatically Send property in the SMS Properties category.

Adding Commands to the Project

  1. Open the Flow Designer.
  2. Choose Exit Command from the Commands section of the Component Palette. Drag and drop it into the smsComposer component in the Flow Designer.

Connecting Components to Create an Application Flow

In the Flow Designer, click on the Start Point on the Mobile Device and drag it to the spalshScreen component. In the same manner, connect the components together as shown in the following graphic.
Shows the Flow Designer with components connected by command lines

Modifying Task for Wait Screen

In the Resources category of the Navigator, find and right-click the task component, choose Go To Source from the popup menu. In the Source window, find section // write task-execution user code here" and replace it with smsComposer.sendSMS();.

Running the Project

Press to Run the main project. Alternatively you could select Run > Run Main Project.



Javadoc for the SMS Composer Component

The NetBeans IDE provides API Javadocs for the SMSComposer component, as well as other components you can use in the VMD. To read the Javadocs for the SMSComposer component:
  1. Place the cursor on the SMSComposer component in the source code and press Ctr-Shift-Space (or choose Source > Show Documentation).
    The Javadoc for this element displays in a popup window.
  2. Click the Show documentation in external web browser icon (Show documentation in external web browser) in the popup window to view the detailed information about the SMSComposer component in your browser.

Creating C and C++ Projects using Net Beans

Requirements

To this tutorial, you need the following software and resources.
Software or Resource Version Required
  • NetBeans IDE         
  • version 6.9 with NetBeans C/C++ plugin
  • Java Developer Kit (JDK)
  • version 6
  • C and C++ compilers, make, gdb
  • C/C++ Tool Collections Tested with NetBeans IDE

Sample Projects
Just want to play with some projects? In the IDE, choose File > New Project, then open the Samples category, the C/C++ subcategory, and the C/C++ subcategory. The IDE provides several sample C and C++ projects to help you familiarize yourself with the IDE.

Creating C and C++ Projects

NetBeans C/C++ support lets you create C and C++ Application and Library projects with generated makefiles, as well as C and C++ projects with existing sources.
You can build, run, and debug your project on the local host (the system from which you started the IDE) or on a remote host running a UNIX® operating system. For information on specifying the tool collection for your project, and on defining and using remote hosts.
With a C/C++ Application, Dynamic Library, or Static Library project, the IDE controls all aspects of how your application is built, run, and debugged. You specify project settings when creating the project and in the Project Properties dialog box. The IDE generates a makefile in which all of your settings are stored.

Creating a C/C++ Application Project

  1. Open the New Project wizard by choosing File > New Project.
  2. In the wizard, select the C/C++ category.
  3. The wizard gives you a choice of several types of new projects. Select C/C++ Application and click Next.
  4. Screenshot of the New Project
           Wizard
  5. Create a new C/C++ Application project from the wizard using the defaults. You can choose the name of the project and the location of the project.
  6. Click Finish to exit the wizard.
A project is created with logical folders. A logical folder is not a directory. It is a way for you to organize your files and does not reflect where the files are physically stored on disk. Files added to logical folders are automatically part of the project and are compiled when you build the project.
Files added to the Important Files folder are not part of the project and are not compiled when you build the project. These files are just for reference and are convenient when you have a project with an existing makefile.

Switching Between the Logical View and the Physical View of the Project

A project has both a logical and a physical view. You can switch between the logical view and the physical view of your project.
  1. Select the Files tab. This window shows the physical view of your project. It displays files and folders as they are stored on disk.
  2. Screenshot of the Files tab
  3. Select the Projects tab. This window shows the logical view of your project.
  4. Screenshot of the Projects tab
    Most commands that you run on a project are available in the Projects view, not the Files view.

Adding Files and Folders to Your Project

You can add logical folders to your project.
  1. Right-click the project node of your Application project and choose New Logical Folder. A new logical folder is added to the project.
  2. Right-click the new logical folder and select Rename. Type the name you would like to give the new folder.
You can add both files and folders to an existing folder. Logical folders can be nested.

Adding New Files to Your Project

You can add new files to your project.
  1. Right-click the Source Files folder and choose New > C Source File.
  2. On the Name and Location page of the New File dialog box, type newfile in the File Name field.

    Screenshot of the New File dialog
              box

  3. Click Finish.
The newfile.c file is created on disk in the directory specified in the wizard and added to the Source Files folder. You can add any kind of file to this folder, not only source files.

Adding More New Files to Your Project

  1. Right-click the Header Files folder and choose New > C Header File.
  2. On the Name and Location page of the New File dialog box, type newfile in the File Name field.
  3. Click Finish.
The newfile.h file is created on disk in the directory specified in the wizard and added to the Header Files folder.

Adding Existing Files to Your Project

You can add existing files to your project in two ways:
  • Right-click the Source Files folder and choose Add Existing Item. You can point to an existing file on disk using the Select Item dialog box and add the file to the project.
  • Right-click the Source Files folder and choose Add Existing Items from Folders. Use the Add Files dialog box to add folders that contain existing files.
Do not use New menu item to add existing items. The Name and Location panel will tell you the file already exists.

Setting Project Properties


When the project is created, it has two configurations, Debug and Release. A configuration is a collection of settings used for the project, which allows you to easily switch many settings at once when you select a configuration. The Debug configuration builds a version of your application that includes debug information. The Release configuration builds an optimized version.
The Project Properties dialog box contains build and configuration information for your project. To open the Project Properties dialog box:
  • Right-click the project node of the CppApplication_1 project and choose Properties.
  • Screenshot of the Project
              Properties dialog box
You can modify the build tool defaults, compiler settings, and other configuration settings in the Project Properties dialog box by selecting a node in the left panel and modifying the properties in the right panel. Select some of the nodes and property values and notice the properties you can set. When you set General properties, you are setting them in all configurations of the project. When you set Build, Run, or Debug properties, you are setting properties in the currently selected configuration.

Managing Configurations

Properties changed in the Project Properties window are stored in the makefile for the current configuration. You can edit the default configurations or create new ones. To create a new configuration:
  1. Click the Manage Configurations button in the Project Properties dialog box.
  2. In the Configurations dialog box, select the configuration that most closely matches your desired configuration. In this case, select the Release configuration and click the Duplicate button. Then click Rename.
  3. In the Rename dialog box, rename the configuration to PerformanceRelease. Click OK.
  4. Click OK in the Configurations dialog box.
  5. In the Project Properties dialog box, note that the PerformanceRelease configuration is selected in the Configuration drop-down list.
  6. In the left panel, select the C Compiler node.
  7. In the property sheet in the right panel, change the Development Mode from Release to PerformanceRelease. Click OK.
You have created a new configuration that will compile the application with a different set of options.

Setting Source File Properties


When you set the project properties for your C or C++ project, the relevant properties apply to all files in the project. You can also set some properties on individual files.
  1. Right-click the newfile.c source file in the Projects window and choose Properties.
  2. Click the General category and see that you can specify a different compiler or other tool to build this file. You can also use a checkbox to exclude the file from the build of the currently selected project configuration.
  3. Click the C Compiler category and see that you can override the project compiler settings and other properties for this file.
  4. Cancel the File Properties dialog box.

Setting the Main Project

When you right-click a project node in the Projects window, you get a pop-up menu of actions you can perform on the selected project. If you have multiple projects open at the same time, the pop-up menu for a project node implies you are operating on that project. But what about project-related actions on the menubar and toolbar?
Most of the project-related actions on the menubar and toolbar operate on the main project. The main project node is displayed in bold text in the Project window. If you have multiple projects open, you might want to change which project is set as the main project so that you can use the toolbar actions on the project.
To change the main project in the IDE:
  • Right-click the desired project node and choose Set as Main Project. This project is now the main project in the IDE and actions in the menubar and toolbar refer to this project.

Building Your Project

To build your project:
  1. Choose Run > Build Main Project and the project builds. The build output is shown in the Output window.
  2. Switch the configuration from Debug to PerformanceRelease in the configuration drop-down list in the main toolbar. Now the project will be built using the PerformanceRelease configuration.
  3. Choose Run > Build Main Project and the project builds. The build output is shown in the Output window.
You can build, clean, or both clean and build the project by choosing actions from the Run menu. The project also keeps object files and executables from different configurations separate, so you do not have to worry about mixing files from multiple configurations.

Compiling a Single File

To compile a single source file:
  • Right-click on the main.c file and choose Compile File. Only this file is compiled.
Single file compilation is not supported for the project type C/C++ Project With Existing Sources.

Running a Project

To see how to run a project, you will use the IDE's sample Arguments project. The Arguments program prints command-line arguments. Before running the program, you will set some arguments in the current configuration. Then you will run the program.
To create the Arguments project, set some arguments, and run the project:
  1. Choose File > New Project.
  2. In the project wizard, expand the Samples category.
  3. Select the C/C++ subcategory, then select the Arguments project. Click Next, then click Finish.
  4. Right-click the Arguments_1 project node and choose Build. The project builds.
  5. Right-click the Arguments_1 project node and choose Properties.
  6. In the Project Properties dialog box, select the Run node.
  7. In the Arguments text field, type 1111 2222 3333. Click OK.
  8. Screenshot of the Project Properties
           dialog box
  9. Choose Run > Run Main Project. The application runs. Your arguments are displayed in an external terminal window.
  10. You may notice the Run Monitor tab, which opens when you run the project. The Run Monitor displays the profiling tools that are available on Linux and Solaris platforms for observing your application's behavior. If you are following this tutorial on Windows or Mac OS X you see a message "To use this feature, the development host operating system must be Solaris or Linux."
    You can turn off the profiling tools using the project's properties Profile category.

Creating a C/C++ Project With Existing Sources

When creating a C/C++ Project With Existing Sources, the IDE relies on your existing makefile for instructions on how to compile and run your application.
In this exercise, you download and install the sources for the open source Loki C++ library. Loki requires the Pthreads library to build, which is available by default on Linux, Solaris, and Mac OS X. If you are using Windows, the Pthreads library must be downloaded before you can create a project using the Loki source files.

Creating a Project With Existing Sources

  1. If you are running the IDE on Windows, install the Pthreads library from http://sourceware.org/pthreads-win32. For convenience, you can use this direct link to the pthreads-2005-03-08.exe installer.
    Extract the pthreads library in your Windows user directory.
  2. Download the loki-0.1.7 library from http://sourceforge.net/projects/loki-lib.
  3. Uncompress loki-0.1.7 in a directory of your choice.
  4. Open the New Project wizard by choosing File > New Project.
  5. Select the C/C++ category.
  6. Select C/C++ Project With Existing Sources and click Next.
  7. On the Select Mode page, click the Browse button. In the Select Project Folder dialog box, navigate to the directory where you saved loki-0.1.7. Select the loki-0.1.7 directory. Click Select.

    Screen shot of Makefile and
           Select Mode page of Project Wizard

  8. Use the default Configuration Mode, Automatic. Click Finish.
  9. The project is created and opened in the Project window, and the IDE automatically runs the Clean and Build actions specified in the existing Makefile. The project is also automatically configured for code assistance. Screen shot of successful
           make of Project with Existing Sources

Building and Rebuilding Your Project

To build the project:
  • Right-click the project node of the project and choose Build.
To rebuild the project:
  • Right-click the project node of the project and choose Clean and Build.

NetBeans IDE PHP Quick Start Tutorial

Installation and Configuration

The following documents contain instructions for one or two ways to set up a PHP web stack on your operating system. These instructions are not definitive. The web stack consists of third-party software, your environment may differ, and you might prefer a different AMP package or another way to set up PHP. You might need to supplement our instructions with your own investigations.
  • Configuring PHP Development Environment in Windows
  • Configuring PHP Development Environment in the Ubuntu Linux Distribution
  • Configuring PHP Development Environment in Mac Operating System (Mac OS X)

Setting up a PHP Project in the NetBeans IDE for PHP

For help in installing and starting NetBeans IDE, please see the installation documentation.
To start PHP development in the NetBeans IDE for PHP, you first need to create a project. A project contains the information on the location of the project files and the way you want to run and debug your application (run configuration).

  1. Start the IDE, switch to the Projects window, and choose File > New Project. The Choose Project panel opens.
  2. In the Categories list, choose PHP.
  3. In the Projects area, choose PHP Application and click Next. The New PHP Project > Name and Location panel opens.
    Name and Location panel of New PHP Project wizard, with Source Folder location as XAmpp document root.
  4. In the Project Name text field, enter NewPHPProject.
  5. In the Sources Folder field, browse for your PHP document root and create a subfolder there called NewPHPProject. The document root is the folder where the web server looks for files to open in the browser. The document root is specified in the web server configuration file. For example, on Xampp, the document root is XAMPP_HOME/htdocs.
  6. Leave all other fields with their default values. Click Next. The Run Configuration window opens.
    Run Configuration panel of New PHP Project wizard, with default values chosen
  7. In the Run As drop-down list, select Local Web Site. The project will run on your local Apache server. Your other options are to run the project remotely via FTP and to run it from the command line.
  8. Leave the Project URL at default.
  9. Click Finish. The IDE creates the project.
Learn more about Setting up a PHP project in NetBeans.

Running Your First PHP Project

  1. Start the IDE, choose File > Open Project. The Open Project dialog box opens.
  2. Select NewPHPProject and click Open Project. The NewPHPProject tree appears in the Projects window and the project's index.php file opens in the editor and in the Navigator window.
    NewPHPProject open in the IDE, showing index.php in editor
  3. Enter the following code inside the block:
    echo "Hello, world! This is my first PHP project!";
  4. To run the project, position the cursor on the NewPHPProject node and choose Run from the context menu. The figure below shows what you should see in the browser window:
    New PHP Project Panel with the fields filled in
    Congratulations! Your program works!

Using Net Beans IDE Developing a Application

Exercise 1: Creating a Project

The first step is to create an IDE project for the application that we are going to develop. We will name our project NumberAddition.
  1. Choose File > New Project. Alternatively, you can click the New Project icon in the IDE toolbar.
  2. In the Categories pane, select the Java node. In the Projects pane, choose Java Application. Click Next.
  3. Type NumberAddition in the Project Name field and specify a path, for example, in your home directory, as the project location.
  4. (Optional) Select the Use Dedicated Folder for Storing Libraries checkbox and specify the location for the libraries folder. See Sharing Project Libraries for more information on this option.
  5. Ensure that the Set as Main Project checkbox is selected.
  6. Deselect the Create Main Class checkbox if it is selected.
  7. Click Finish.

Exercise 2: Building the Front End

To proceed with building our interface, we need to create a Java container within which we will place the other required GUI components. In this step we'll create a container using the JFrame component. We will place the container in a new package, which will appear within the Source Packages node.

Create a JFrame container

  1. In the Projects window, right-click the NumberAddition node and choose New > Other.
  2. In the New File dialog box, choose the Swing GUI Forms category and the JFrame Form file type. Click Next.
  3. Enter NumberAdditionUI as the class name.
  4. Enter my.numberaddition as the package.
  5. Click Finish.
The IDE creates the NumberAdditionUI form and the NumberAdditionUI class within the NumberAddition application, and opens the NumberAdditionUI form in the GUI Builder. The my.NumberAddition package replaces the default package.

Adding Components: Making the Front End

Next we will use the Palette to populate our application's front end with a JPanel. Then we will add three JLabels, three JTextFields, and three JButtons. If you have not used the GUI Builder before, you might find information in the Designing a Swing GUI in NetBeans IDE tutorial on positioning components useful.
Once you are done dragging and positioning the aforementioned components, the JFrame should look something like the following screenshot.
screenshot of JFrame with 3 JLabels, 3 JButtons, and 3 JTextFields If you do not see the Palette window in the upper right corner of the IDE, choose Window > Palette.
  1. Start by selecting a Panel from the Swing Containers category on Palette and drop it onto the JFrame.
  2. While the JPanel is highlighted, go to the Properties window and click the ellipsis (...) button next to Border to choose a border style.
  3. In the Border dialog, select TitledBorder from the list, and type in Number Addition in the Title field. Click OK to save the changes and exit the dialog.
  4. You should now see an empty titled JFrame that says Number Addition like in the screenshot. Look at the screenshot and add three JLabels, three JTextFields and three JButtons as you see above.

Renaming the Components

In this step we are going to rename the display text of the components that were just added to the JFrame.
  1. Double-click jLabel1 and change the text property to First Number
  2. Double-click jLabel2 and change the text to Second Number
  3. Double-click jLabel3 and change the text to Result
  4. Delete the sample text from jTextField1. You can make the display text editable by right-clicking the text field and choosing Edit Text from the popup menu. You may have to resize the jTextField1 to its original size. Repeat this step for jTextField2 and jTextField3.
  5. Rename the display text of jButton1 to Clear. (You can edit a button's text by right-clicking the button and choosing Edit Text. Or you can click the button, pause, and then click again.)
  6. Rename the display text of jButton2 to Add.
  7. Rename the display text of jButton3 to Exit.
Your Finished GUI should now look like the following screenshot:
screenshot of the completed application

Exercise 3: Adding Functionality

In this exercise we are going to give functionality to the Add, Clear, and Exit buttons. The jTextField1 and jTextField2 boxes will be used for user input and jTextField3 for program output - what we are creating is a very simple calculator. Let's begin.

Making the Exit Button Work

In order to give function to the buttons, we have to assign an event handler to each to respond to events. In our case we want to know when the button is pressed, either by mouse click or via keyboard. So we will use ActionListener responding to ActionEvent.
  1. Right click the Exit button. From the pop-up menu choose Events > Action > actionPerformed. Note that the menu contains many more events you can respond to! When you select the actionPerformed event, the IDE will automatically add an ActionListener to the Exit button and generate a handler method for handling the listener's actionPerformed method.
  2. The IDE will open up the Source Code window and scroll to where you implement the action you want the button to do when the button is pressed (either by mouse click or via keyboard). Your Source Code window should contain the following lines:
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
        //TODO add your handling code here:
                    }
  3. We are now going to add code for what we want the Exit Button to do. Replace the TODO line with System.exit(0);. Your finished Exit button code should look like this:
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
        System.exit(0);
                    } 

Making the Clear Button Work

  1. Click the Design tab at the top of your work area to go back to the Form Design.
  2. Right click the Clear button (jButton1). From the pop-up menu select Events > Action > actionPerformed.
  3. We are going to have the Clear button erase all text from the jTextFields. To do this, you will add some code like above. Your finished source code should look like this:
  4. private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
        jTextField1.setText("");
        jTextField2.setText("");
        jTextField3.setText("");
                    }
The above code changes the text in all three of our JTextFields to nothing, in essence it is overwriting the existing Text with a blank.

Making the Add Button Work

The Add button will perform three actions.
  1. It is going to accept user input from jTextField1 and jTextField2 and convert the input from a type String to a float.
  2. It will then perform addition of the two numbers.
  3. And finally, it will convert the sum to a type String and place it in jTextField3.
Lets get started!
  1. Click the Design tab at the top of your work area to go back to the Form Design.
  2. Right-click the Add button (jButton2). From the pop-up menu, select Events > Action > actionPerformed.
  3. We are going to add some code to have our Add button work. The finished source code shall look like this:
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt){
        // First we define float variables.
        float num1, num2, result;
        // We have to parse the text to a type float.
        num1 = Float.parseFloat(jTextField1.getText());
        num2 = Float.parseFloat(jTextField2.getText());
        // Now we can perform the addition.
        result = num1+num2;
        // We will now pass the value of result to jTextField3.
        // At the same time, we are going to
        // change the value of result from a float to a string.
        jTextField3.setText(String.valueOf(result));
                        }
Our program is now complete we can now build and run it to see it in action.

Exercise 4: Running the Program

To run the program in the IDE:
  1. Choose Run > Run Main Project (alternatively, press F6).
  2. If you get a window informing you that Project NumberAddition does not have a main class set, then you should select my.NumberAddition.NumberAdditionUI as the main class in the same window and click the OK button.
To run the program outside of the IDE:
  1. Choose Run > Clean and Build Main Project (Shift-F11) to build the application JAR file.
  2. Using your system's file explorer or file manager, navigate to the NumberAddition/dist directory.
  3. Double-click the NumberAddition.jar file.
After a few seconds, the application should start.
Note: If double-clicking the JAR file does not launch the application.
You can also launch the application from the command line.
To launch the application from the command line:
  1. On your system, open up a command prompt or terminal window.
  2. In the command prompt, change directories to the NumberAddition/dist directory.
  3. At the command line, type the following statement:
    java -jar  NumberAddition.jar

How Event Handling Works

This tutorial has showed how to respond to a simple button event. There are many more events you can have your application respond to. The IDE can help you find the list of available events your GUI components can handle:
  1. Go back to the file NumberAdditionUI.java in the Editor. Click the Design tab to see the GUI's layout in the GUI Builder.
  2. Right-click any GUI component, and select Events from the pop-up menu. For now, just browse the menu to see what's there, you don't need to select anything.
  3. Alternatively, you can select Properties from the Window menu. In the Properties window, click the Events tab. In the Events tab, you can view and edit events handlers associated with the currently active GUI component.
  4. You can have your application respond to key presses, single, double and triple mouse clicks, mouse motion, window size and focus changes. You can generate event handlers for all of them from the Events menu. The most common event you will use is an Action event. 
How does event handling work? Every time you select an event from the Event menu, the IDE automatically creates a so-called event listener for you, and hooks it up to your component. Go through the following steps to see how event handling works.
  1. Go back to the file NumberAdditionUI.java in the Editor. Click the Source tab to see the GUI's source.
  2. Scroll down and note the methods jButton1ActionPerformed(), jButton2ActionPerformed(), and jButton3ActionPerformed() that you just implemented. These methods are called event handlers.
  3. Now scroll to a method called initComponents(). If you do not see this method, look for a line that says Generated Code; click the + sign next to it to expand the collapsed initComponents() method.
  4. First, note the blue block around the initComponents() method. This code was auto-generated by the IDE and you cannot edit it.
  5. Now, browse through the initComponents() method. Among other things, it contains the code that initializes and places your GUI components on the form. This code is generated and updated automatically while you place and edit components in the Design view.
  6. In initComponents(), scroll down to where it says
    jButton3.setText("Exit");
    jButton3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
               jButton3ActionPerformed(evt);
        }
                });

Eclipse Shortcuts


Eclipse Shortcuts

Editors are an integral part of a programmer’s life. If you have good proficiency in using an editor thats a great advantage. It comes very handy to debug. Traditional notepad and SOPs (System.out.println) are the way we start learning a language but that is not sufficient, so beginners start using an IDE and most importantly know the shortcuts.
For java developers there is a huge list and some popular areEclipse, Netbeans, IntelliJ Idea. I use Eclipse as my IDE and vim as a light weight editor.

This article is for those who use or intend to use Eclipse as IDE. Keyboard shortcuts are very important for comfortable and quick editing. I have abridged the following list of eclipse shortcuts from my own experience and literature.
There is a huge list of eclipse shortcuts available but I have listed only the most essential ones that you may need daily. 
File Navigation – Eclipse Shortcuts
  • CTRL SHIFT R – Open a resource. You need not know the path and just part of the file name is enough.
  • CTRL E – Open a file (editor) from within the list of all open files.
  • CTRL PAGE UP or PAGE DOWN – Navigate to previous or next file from within the list of all open files.
  • ALT <- or ALT -> – Go to previous or next edit positions from editor history list.
Java Editing – Eclipse Shortcuts
  • CTRL SPACE – Type assist
  • CTRL SHIFT F – Format code.
  • CTRL O – List all methods of the class and again CTRL O lists including inherited methods.
  • CTRL SHIFT O – Organize imports.
  • CTRL SHIFT U – Find reference in file.
  • CTRL / – Comment a line.
  • F3 – Go to the declaration of the variable.
  • F4 – Show type hierarchy of on a class.
  • CTRL T – Show inheritance tree of current token.
  • SHIFT F2 – Show Javadoc for current element.
  • ALT SHIFT Z – Enclose block in try-catch.
General Editing – Eclipse Shortcuts
  • F12 – Focus on current editor.
  • CTRL L – Go to line number.
  • CTRL D – Delete a line.
  • CTRL <- or -> – Move one element left or right.
  • CTRL M – Maximize editor.
  • CTRL SHIFT P – Go to the matching parenthesis.
Debug, Run – Eclipse Shortcuts
  • CTRL . or , – Navigate to next or previous error.
  • F5 – Step into.
  • F6 – Step over.
  • F8 – Resume
  • CTRL Q – Inspect.
  • CTRL F11 – Run last run program.
  • CTRL 1 – Quick fix code.
Search – Eclipse Shortcuts
  • CTRL SHIFT G – Search for current cursor positioned word reference in workspace
  • CTRL H – Java search in workspace.                                                                                                      File Navigation
    CTRL SHIFT R Open a resource
    CTRL E Open a file (editor) from within the list of all open files
    CTRL PAGE UP or PAGE DOWN Navigate to previous or next file from within the list of all open files
    ALT <- or ALT -> Go to previous or next edit positions from editor history list
    Java Editing
    CTRL SPACE Type assist
    CTRL SHIFT F Format code
    CTRL O List all methods of the class
    CTRL SHIFT O Organize imports
    CTRL SHIFT U Find reference in file
    CTRL / Comment a line
    F3 Go to the declaration of the variable
    F4 Show type hierarchy of on a class
    CTRL T Show inheritance tree of current token
    SHIFT F2 Show Javadoc for current element
    ALT SHIFT Z Enclose block in try-catch
    General Editing
    F12 Focus on current editor
    CTRL L Go to line number
    CTRL D Delete a line
    CTRL <- or -> Move one element left or right
    CTRL M Maximize editor
    CTRL SHIFT P Go to the matching parenthesis
    Debug, Run
    CTRL . or , Navigate to next or previous error
    F5 Step into
    F6 Step over
    F8 Resume
    CTRL Q Inspect
    CTRL F11 Run last run program
    CTRL 1 Quick fix code
    Search
    CTRL SHIFT G Search for current cursor positioned word reference in workspace
    CTRL H Java search in workspace