Tuesday, October 11, 2011

Send mail using Jsp and Servlet.

 Hello firends,

using this blog you can send mail using JSP and Servlets, follow the following steps to design this application


Send mail using Jsp and Servlet.
  1.    Create new web project using netbean. 
  2.       For this project following 5 labraries are requered.
a.       activation.jar
b.      mail.jar
c.       mailapi.jar
d.      pop3.jar
e.      smtp.jar
3.       After adding this library in project bellow code is copy and paste in index.jsp file.

index.jsp
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Java Mail</title>
    </head>
    <body>
        <form action="sendMail.jsp" method="POST">
            <table border="0" align="center" cellpadding="5">
                <tbody>
                    <thead><tr> <td colspan="3" align="center">
                    <b> Send Mail </b> </td> </tr> </thead>
                    <tr>
                        <td> To </td> <td> : </td>
                        <td> <input type="text" name="to" value="" /> </td>
                    </tr>
                    <tr>
                        <td> Subject </td> <td> : </td>
                        <td> <input type="text" name="subject" value="" /> </td>
                    </tr>
                    <tr>
                        <td> Message </td> <td> : </td>
                        <td> <textarea name="message" rows="8" cols="30">
                        </textarea></td>
                    </tr>
                    <tr>
                        <td colspan="3" align="center">
                        <input type="submit" value="Send Mail" />

                        <input type="reset" value="Reset" />
                        <td>
                    </tr>
                </tbody>
            </table>
        </form>
    </body>
</html>


Screen of index.jsp


sendMail.jsp
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Send Mail</title>
    </head>
    <body>
        <jsp:useBean id="mail" scope="session" class="jMail.Mail" />
        <jsp:setProperty name="mail" property="to" param="to" />
        <jsp:setProperty name="mail" property="from"  value="smaple@gmail.com" />

                <!-- Note:  value = add your email id hear -->

        <jsp:setProperty name="mail" property="smtpServ" value="smtp.gmail.com" />
        <jsp:setProperty name="mail" property="subject" param="subject" />
        <jsp:setProperty name="mail" property="message" param="message" />

        <%
String to = mail.getTo();
int result;
result = mail.sendMail();
if(result == 0){
    out.println(" Mail Successfully Sent to "+to);
}
else{
    out.println(" Mail NOT Sent to "+to);
}
       %>
    </body>
</html>






Java File: 

Mail.java


package jMail;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class Mail {
    private String to;
    private String from;
    private String message;
    private String subject;
    private String smtpServ;


    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }
    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getSmtpServ() {
        return smtpServ;
    }
    public void setSmtpServ(String smtpServ) {
        this.smtpServ = smtpServ;
    }

public int sendMail(){
        try
        {
            Properties props = System.getProperties();
              // -- Attaching to default Session, or we could start a new one --
              props.put("mail.transport.protocol", "smtp" );
              props.put("mail.smtp.starttls.enable","true" );
              props.put("mail.smtp.host",smtpServ);
              props.put("mail.smtp.auth", "true" );
              Authenticator auth = new SMTPAuthenticator();
              Session session = Session.getInstance(props, auth);
              // -- Create a new message --
              Message msg = new MimeMessage(session);
              // -- Set the FROM and TO fields --
              msg.setFrom(new InternetAddress(from));
              msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
              msg.setSubject(subject);
              msg.setText(message);
              // -- Set some other header information --
              msg.setHeader("MyMail", "Mr. XYZ" );
              msg.setSentDate(new Date());
              // -- Send the message --
              Transport.send(msg);
              System.out.println("Message sent to"+to+" OK." );
              return 0;
        }
        catch (Exception ex)
        {
          ex.printStackTrace();
          System.out.println("Exception "+ex);
          return -1;
        }
  }

// Also include an inner class that is used for authentication purposes

private class SMTPAuthenticator extends javax.mail.Authenticator {
        @Override
  public PasswordAuthentication getPasswordAuthentication() {
         String username =  "sender@gmail.com";           // specify your email id here (sender's email id)
         String password = "password";                             // specify your password here
        return new PasswordAuthentication(username, password);
     }
  }
}




After complete the coding run the project.
                If any problem face then contact me at  “ xijay.ss@gmail.com “ and this project is also available at  www.project –source-code.com download and use.
Linlks:

http://zetcode.com/tutorials/jeetutorials/sendingemail/
http://ajayshilwant.blogspot.com/2011/05/send-mail-using-jsp-and-servlet.html

Send email with Attachments:



import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SendAttachment extends HttpServlet {


public SendAttachment() {
super();
}


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

response.setContentType("text/html");
PrintWriter out = response.getWriter();
String to = "balaram36@gmail.com";// change accordingly
final String user = "balaram.amma@gmail.com";// change accordingly
final String password = "hibernate";// change accordingly

// 1) get the session object
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", "smtp.gmail.com");// change
// accordingly
properties.put("mail.smtp.auth", "true");

Session session = Session.getDefaultInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});

// 2) compose message
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
to));
message.setSubject("Message Aleart");

// 3) create MimeBodyPart object and set your message content
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("This is message body");

// 4) create new MimeBodyPart object and set DataHandler object to
// this object
MimeBodyPart messageBodyPart2 = new MimeBodyPart();

String file = "C:\\Documents and Settings\\suresh\\My Documents\\Downloads\\Compressed\\SendAttachment.java";// change accordingly

DataSource source = new FileDataSource(file);
messageBodyPart2.setDataHandler(new DataHandler(source));
String filename=file.substring(file.lastIndexOf("\\")+1);
messageBodyPart2.setFileName(filename);

// 5) create Multipart object and add MimeBodyPart objects to this
// object
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);

// 6) set the multiplart object to the message object
message.setContent(multipart);

// 7) send message
Transport.send(message);

System.out.println("message sent....");
} catch (MessagingException ex) {
ex.printStackTrace();
}
}

}



Saturday, October 8, 2011

MyEclipse Shortcuts

Navigational Shortcuts
F10 Main menu
Shift F10 Context menu
Ctrl F10 View menu
   
Workspace navigation
F12 Activate editor
Ctrl+Shift+W Switch editor
Ctrl F6 Next editor
Ctrl Shift F6 Prev editor
Ctrl F7 Next workspace
Ctrl Shift F7 Prev workspace
Ctrl F8 Next perspective
Ctrl Shift F8 Prev perspective
Alt Left Back
Alt Right Forward
   
Files
Alt Shift S Show in…
Ctrl Shift R Jump to file
Ctrl N New file
Ctrl S Save file
Ctrl Shift S Save all files
Ctrl F4 Close file
Ctrl Shift F4 Close all files
   
Find
Ctrl L Goto line
Ctrl F Find
Ctrl J Incremental find
Ctrl Shift J Incremental find prev
Ctrl K Find next
Ctrl Shift K Find prev
Ctrl H Search workspace
Ctrl (dot) Navigate next
Ctrl (comma) Navigate prev
   
Java navigation
F3 Goto declaration
Ctrl Shift U Find references in file
Ctrl Shift G Find references in workspace
Ctrl G Find declarations in workspace
Ctrl Shift P Navigate to matching bracket/brace
Ctrl T Popup type hierarchy
Ctrl Shift T Open Type
Ctrl O Outline of current source
Ctrl F3 Outline of current cursor position
Ctrl Shift Arrow Jump beetween methods up or down
F2 Show Javadoc
F4 Show hierarchy
Ctrl Alt H Open call hierarchy
   
   
General editing
Alt Arrow Move line(s) up or down
Alt Shift Up Expand selection to enclosing element
Alt Shift Right Expand selection to next element
Alt Shift Left Expand selection to previous element
Alt Shift Down Restore previous selection
Ctrl Alt Arrow Duplicate line(s) up or down
Shift Enter Insert line below
Ctrl Shift Enter Insert line above
Ctrl D Delete line
Ctrl Shift Q Toggle Quick Diff
Ctrl Shift Y Convert to lowercase
Ctrl Shift X Convert to uppercase
   
Java editing
Alt Shift U Remove occurrence annotations
Ctrl 1 Quick fix (works even when there are no errors
Ctrl Shift M Add import
Ctrl Shift F Reformat
Ctrl Shift O Organize Imports
Ctrl / Comment
Ctrl \ UnComment
Ctrl Shift Space Parameter hints
Ctrl Hyperlink identifier
Ctrl I Correct indentation
Shift Space Incremental content assist
   
Debugger
F5 Step into
F6 Step over
F7 Run to return
F8 Resume
F9 Relaunch last
F11 Run/debug last
Ctrl F11 Run
Ctrl Shift B Toggle breakpoint
Ctrl D Display
Ctrl Q Inspect
Ctrl R Run to line
Ctrl U Run snippet
   
Refactoring
Alt T Refactoring menu
Ctrl Shift Z Undo refactor
Ctrl Shift Y Redo refactor
Alt Shift R Rename
Alt Shift V Move
Alt Shift I Inline
Alt Shift M Extract method
Alt Shift L Extract local
Alt Shift C Change method signature
   
Misc
F5 Refresh
F1 Infopop
F2 Show resizeable hover

MyEclipse JSF Tutorial

Outline




 

1. Preface

This document was written using MyEclipse. However, if you notice discrepancies between this document and the version of MyEclipse you are using to perform the install that make it difficult or impossible to follow this guide, please see the User Feedback section on how to

 

2. Introduction

In this tutorial we will be walking through a small JSF demo application using MyEclipse. Previous knowledge of JSF and/or MyEclipse is not necessary, but would be helpful.

Since Struts is such a prevalent web application framework, similarities between JSF and Struts will be noted, wherever appropriate, to help the reader with previous Struts experience. However, if you have no prior experience with Struts, you may feel free to skip those sections.

3. Requirements

Below is a list of software used by this guide:
  • MyEclipse (download available here)
  • For this demo the User Name is "myeclipse" and the Password is "myeclipse" as well.

4.  New Project Setup & Structure 

To organize our development artifacts, we will need to create a new Web Module Project in MyEclipse that has JSF Capabilities added to it.  You can create a web project by selecting Web Project from the new toolbar menu:

Figure 4.1: Create a new web project

Figure 4.2: Web Project Wizard Dialog
The wizard will allow you to customize your project settings by entering your preferences into the dialog fields, as demonstrated in Figure 4.2.
NoteIt is popular when developing JSF applications to also use the JSTL libraries, so selecting add "JSTL Libraries" during project creation is recommended.  However, it is also possible to add the JSTL libraries later, via the "Add JSTL Libraries" item from the MyEclipse context menu.
Once the Web Project is created, we need to add JSF Capabilities to it. This is done by right clicking on the root of our project in the Package Explorer View, and selecting MyEclipse > Add JSF Capabilities, as shown in Figure 4.3.

Figure 4.3: Adding JSF Capabilities to a Web Project
The default values for the JSF dialog are fine for the purposes of this tutorial.  Advanced users may perform additional configuration by changing the default settings in the dialog, as shown in Figure 4.4.

Figure 4.4: Configuring JSF Capabilities
After the wizard completes, the project structure will look like what is shown in Figure 4.5.

Figure 4.5: Project Layout After Configuration
Now that the project has been created, we can start editing and creating our application.

5. Creating the Message Bundle

Let's start off our new application with the creation of the MessageBundle file. This is a simple property file that stores all our messages along with their associated keys.  Then the bundle can be used in any of our JSP pages to allow our application to be easily internationalized.  As an analogy, Struts provided similar support in this area by using the ApplicationResources.properties file,  the various <bean /> tags, and the message bundle attributes that the bean tags accepted.

In JSF, we can load a message bundle into a page with the line:
<f:loadBundle basename="com.jsfdemo.MessageBundle" var= "bundle"/>

Note: This line of code creates a page-scoped message bundle that we can reference later in the page via the 'bundle' variable name, use to lookup messages keys, and return the associated message value.

Before creating the message bundle file, create a  com.jsfdemo package in the source folder by right-clicking it and selecting New > Package.   To create the message bundle file, we'll use the New File Wizard that is accessed from the context menu of the project by right-clicking on the project's 'source' folder and selecting New > File.
The new file is opened in the MyEclipse Properties Editor.
After successfully creating the new message bundle file, we need to fill the file with key/value pairs for each label or text string that we want to display in the JSP page. Add the contents from Figure 5.2 by clicking on the Add button, provide values for Name and Value in the Add Property dialog and click Finish.
MessageBundle.properties
user_name_label=User Name:
user_password_label=Password:
login_button_label=Login

Figure 5.1: Contents of MessageBundle.properties
After adding the properties, the MessageBundle.properties file will look like the one shown in Figure:5.2


Figure 5.2: MessageBundle.properties
file
When specifying the file location, select Browse..., choose the directory /JSFLoginDemo/src/com/jsfdemo, name the file MessageBundle.properties, and select Finish.
Now that we have the MessageBundle complete, in the next section we will create the ManagedBean now that will handle our user logging in.

6. Creating the Managed Beans

In this section we'll see how to create the ManagedBean that will perform the login operation when prompted by the login JSP page as well as store the user name and password entered by the user. For the purpose of this demo, the login operation simply checks if the username and password are both "myeclipse"  and then redirects the user to the userLoginSuccess.jsp page.  Otherwise it sends them back to the login page.
First open up the faces-config.xml file with the MyEclipse JSF Editor:

Figure 6.1: Opening faces-config.xml file for editing
Open Tree page and select Managed Beans node on the tree. Press Add... to open new managed bean wizard. Figure 6.2:

Figure 6.2: Launch the managed bean wizard
You will then be presented with the new Managed Bean wizard;  Fill out the values as shown in Figures 6.3 below:

Figure 6.3: Setup the new managed bean
Press "Add..." next to managed properties list to add a new property:

Figure 6.4: Managed bean editor
Fill managed property wizard as described below to create a password property:

Figure 6.5: Managed bean property wizard
Repeat for userName property.
You will now notice that the new UserBean was added to the Outline View as shown in Figure 6.6:

Figure 6.6: UserBean now shown in the Outline View
Open UserBean.java source file will also be opened in the java editor:

Figure 6.7: UserBean Java source opened up in an editor
Notice that the getters and setters for our two properties (username and password) were already generated for us, so the only thing we need to add to this class is the implementation of the loginUser method that will be called to process the user login.
The code snippet for the loginUser method is in Figure 6.8 below.  Please copy and paste it into your file, adding any new imports as necessary:
UserBean.java
    public String loginUser() {
        if("myeclipse".equals(getUserName()) && "myeclipse".equals(getPassword()))
            return "success";
       
        FacesContext facesContext = FacesContext.getCurrentInstance();
        FacesMessage facesMessage = new FacesMessage(
            "You have entered an invalid user name and/or password");
        facesContext.addMessage("loginForm", facesMessage);
       
        return "failure";
    }
Figure 6.8: loginUser code for the new UserBean.java file

Looking at the bean code, we can notice some unique properties about it. For example, the UserBean class doesn't extend or implement any classes or interfaces tied to JSF. It is simply a javabean that includes the additional logic to perform a useful operation.  In Struts terms, it contains all the functionality of a Struts Form and a Struts Action, conveniently located in one class.

Another thing to note is that unlike Struts, these methods do not return special classes, like an ActionForward, because navigation is specified externally in a declarative fashion in the faces-config.xml deployment descriptor.  And, in Section 8 we will show how this descriptor is created and configured.

7. Creating the JSP Pages

In this section we are going to focus on creating the JSP pages for our example JSF application, which will mimic a simple website login screen.  As a result, we will only need 2 JSP pages, one to prompt the user to login and the other to indicate that login was successful.  We will call these pages loginUser.jsp and loginUserSuccess.jsp, respectively. For simplicity, if there is an authorization error during the login attempt, we will redirect the user back to the loginUser.jsp page.  To avoid confusion, we are not using any validation in this demo, but you can easily add validators to the two inputText/Secret JSF components.  We will use these fields to validate the user's entry for length and additionally display an error message if the login was incorrect.
MyEclipse also provides tools that make it simple to create the web pages for our JSF application by editing the faces-config.xml file in the MyEclipse JSF Editor. So make sure that file is still open and we can get started creating our userLogin.jsp page.
To create our userLogin.jsp page we are going to first click the JSP button, then click on our canvas.  When the new JSP wizard comes up, type in the File Name and select the JSF template as shown in Figure 7.1:

Figure 7.1: Creating userLogin.jsp using the faces-config.xml editor

We can also create our userLoginSuccess.jsp now in the same manner:

Figure 7.2: Creating userLoginSuccess.jsp using the faces-config.xml editor

Let's start working on our application now by opening up the userLogin.jsp page:

Figure 7.3: Begin editing the userLogin.jsp page
Now, what we need to do now on this page is:
  • Add an h:inputText component for the user name
  • Add an h:inputSecret component for the password
  • Add an h:outputLabel for the user name inputText
  • Add an h:outputLabel for the password
First thing we need to do is remove the default template text as well as type in our bundle basename so our page can use our MessageBundle.  We will end up with JSP that looks like Figure 7.4:

Figure 7.4: Remove template text and add our MessageBundle to the JSP page

Figure 7.4a: Create the new form
In Figure 7.4a we create the new HTML form element that will contain our login controls. Now we need to actually create the input text boxes!
Now let's create our h:inputText component for the user name, this is shown in Figures 7.6 and 7.7:

Figure 7.6: Adding new inputText component


Figure 7.7: Adding new inputText component continued
Now let's add our h:inputSecret component (no labels yet):

Figure 7.8 Adding new inputSecret component

Figure 7.9 Adding new inputSecret component continued
Now let's add the outputLabel's for both of our input components, starting with our userLabel:


Figure 7.10: Adding outputLabel component to our userName component
We will also need to add a label for our h:inputSecret component in the same manner. After we are done, as mentioned above, let's manually change our h:outputLabel components to wrap h:outputText components that are bound to our MessageBundle so we can see them in the designer, it will look something like this:

Figure 7.11: Adding outputText components to our labels
Be sure to make the modification to both the userName label and password label.
Now it is time to add our login button, we will do that almost identically to how we have added the other components so far, as shown in Figures 7.12 and 7.13:

Figure 7.12: Adding a new commandButton component

Figure 7.13: Adding a new commandButton component continued
Now we have a page that looks something like this:

Figure 7.14: Our almost-complete userLogin.jsp page
You might notice that everything looks pretty ugly on 1 line, so let's add some space to put things on separate lines:

Figure 7.15: Nicely laid out userLogin.jsp page

Now that our userLogin.jsp page is done, let's quickly do our userLoginSuccess.jsp page which is much simpler. Open that file up and edit it, simply adding a line to print out the name of the user that logged in as shown in Figure 7.16:

Figure 7.16: Making userLoginSuccess.jsp page print out the user's name
Now that we have created our two pages, the only thing left for us to do is hook them together with proper Navigation Cases, that is done by visual editing our faces-config.xml file, so open that file. After the file is open for editing, perform the following steps to create the navigation case: 
  1. Click the Navigation Case tool
  2. Click your userLogin.jsp file
  3. Then click on your userLoginSuccess.jsp file
  4. You will be prompted with a wizard to create the navigation case.
Follow Figures 7.17 and 7.18 for creating the success navigation case. In order to create the failure navigation case, we simply do the same steps as before but click twice on the userLogin.jsp file, in order to create a circular navigation case.


Figure 7.17: Creating the success navigation case

Figure 7.18: Creating the success navigation case continued
After we have created both navigation cases, our file will look something like this:

Figure 7.19: Reviewing navigation cases for our app
Now that we have created all our JSP pages and added our Navigation Cases correctly, the only thing left is to run our application!

8. Running the Application

In this section we will quickly show what our new application looks like when its running.

Select your project in the Package Explorer. Expand Run... dropdown. In the Run As menu select MyEclipse Server Application.

Figure 8.1: Run your project as server application
The output from the server log will be redirected to the Eclipse Console View.  From the log shown in Figure 8.2, it is evident that the sever started successfully.

Figure 8.2: Tomcat Startup Log
Once Tomcat is running,  we can test it by opening the MyEclipse Browser View.  This can be done by clicking the Browser button as shown in Figure 8.3.

Figure 8.3: Opening the Web Browser View
 In the browser's address bar, enter http://localhost:8080/JSFLoginDemo/userLogin.faces to activate the example application, as shown in Figure 8.7.
NOTE : The reason the URL ends in .faces and not .jsp is because above, we mapped our FacesServlet to the *.faces extension, that means in order for JSF to be given a chance to process the request and build out the component tree, we must use the .faces extension to access the actual pages. If you don't, you will get an exception along the lines of "FacesContext cannot be found".

Figure 8.4: Accessing the Example Application
Now type in myeclipse for the user name and password and click Login to see your app in action!

Figure 8.5: Logging in...

Figure 8.6: Successful Login
We see our navigation rules kick in as we are validated and directed to the userLoginSuccess.jsp page where our name is displayed. While this application is certainly simple, it does convey the basics of developing a JSF application using MyEclipse.

Building Web Application With Ant and Deploying on Jboss 3.0

Building Web Application With Ant and Deploying on Jboss 3.0 Building Web Application With Ant and Deploying on Jboss 3.0 Previous Tutorial Index Next In this lesson I will show you how to build you web application and install on the Jboss 3.0

Building Web Application With Ant and Deploying on Jboss 3.0

     
In this lesson I will show you how to build you web application and install on the Jboss 3.0 application server.
After the completion of the lesson you will be able to include jsp, html and servlets in the ear file and deploy on the Jboss 3.0 application server. This example will provide a strong foundation for the further development. Ant script developed in this lesson will be used in subsequent tutorial for the development and deployment of complex J2EE Applications with little or no more modification.
In this lesson we will write one Hello World Servlet and a JSP file file to call Hello World Servlet. In order to deploy components we have to build .ear file which is the standard format for the deployment of J2EE application.
First of all let's understand the structure of .ear and .war files.
Enterprise Archive Contents
Enterprise Archive (.ear) component follows the standard directory structure defined in the J2EE specification. 
Directory Structure of .ear archive
 /
  .war and .jar files
  Meta-inf
      application.xml
    
In the .ear file .war,.jar and application.xml file are packaged in the above format.
Enterprise Archive Contents
Web component follows the standard directory structure defined in the J2EE specification. 
Directory Structure of Web Component
 /
   index.htm, JSP, Images etc..
  Web-inf
   web.xml
   classes
     servlet classes
   lib
     jar files
    
Root directory of the web archive ('.war' file) contains all the html, jsp, images files and the additional directories containing these files. In the root directory there is a special directory 'Web-inf' which contains the web deployment descriptor (web.xml), classes and the lib directory.  
Directory Structure of Example2 directory
After understanding the structure of .ear and .war file let's look at the directory structure of example2 directory where we have work to develop the deployable .ear file.
Directory structure:

Description of Directory and its content:
Directory Description
example2 Base directory which contains build.xml and the .ear file generated by Ant utility will be placed here.
build Various files generated by Ant utility will be placed in different directories under this directory. 
build/deploymentdesciptors Web.xml and application.xml files are placed in this directory.
build/ear Intermediate files for the assembling of example2.ear ear file are placed here.
build/jar Any jar file if required will be placed in this directory.
build/war Intermediate files for the assembling of example2.war ear file are placed here.
build/src All the compiled .class files are placed in this directory.
src All the java source files are placed here.
web All the html,jsp, images etc. files are placed in this directory.
In this lesson we creating HelloWorld.java and index.jsp which is in the /src and /web directory respectively.
Source code of HelloWorld.java:
/* * HelloWorld.java
*
*/
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* The Hello World Servelet.
*
* @author Deepak Kumar
* http://www.roseindia.net
* deepak@roseindia.net
*/
public class HelloWorld extends HttpServlet {

public void service(HttpServletRequest request,
HttpServletResponse response) throws  IOException, ServletException{
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  out.println("<html>");
  out.println("<head>");
  out.println("<title>Hello World Servlet!</title>");
  out.println("</head>");
  out.println("<body>");
  out.println("<p align=\"center\"><font size=\"5\" color=\"#000080\">Hello World!</font></p>");
  out.println("<p align=\"center\"><a href=\"javascript:history.back()\">Go to Home</a></p>");
  out.println("</body>");
  out.println("</html>");
   }
}
    
Here is the code of index.jsp file:
 <%@page language="java" %>
<html>

<head>
<title>Welcome to Jboss 3.0 tutorial</title>
</head>

<body bgcolor="#FFFFCC">

<p align="center"><font size="6" color="#800000">Welcome to<br>
Jboss 3.0 Tutorial</font></p>
<p align="center"><font color="#000080" size="4">Congralutations you have successfully
installed lesson 2 tutorial</font></p>
<p align="center"><font color="#000080" size="4"><a href="servlet/HelloWorld">Click here
to</a> execute Hello World Servlet.</font></p>
<p><font size="4">&nbsp;</font></p>
<p align="center"><font color="#000080"><font size="4">For more tutorials and examples visit
</font> </font><font size="4"><a href="http://www.rosindia.net"><font color="#000080">http://www.rosindia.net</font></a></font></p>
<p align="center"><font size="4">&nbsp;</font></p>
<p align="center"><font color="#000080">Copyright © 2001 roseindia.net. All
rights reserved.</font></p>

</body>

</html>

    
You can download all the file of this tutorial from here.
Writing Application and Web deployment descriptor
Since in this lesson we are developing one servlet and one jsp files so our deployment descriptor is very simple.
web.xml file:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>
<servlet>
   <servlet-name>HelloWorld</servlet-name>
  <servlet-class>HelloWorld</servlet-class>
</servlet>

<servlet-mapping>
  <url-pattern>/servlet/HelloWorld</url-pattern>
  <servlet-name>HelloWorld</servlet-name>
</servlet-mapping>

</web-app>


    
application.xml file:

<?xml version="1.0" encoding="ISO-8859-1"?>

<application>
<display-name>Example 2 </display-name>
<module>
<web>
<web-uri>example2.war</web-uri>
<context-root>/example2</context-root>
</web>
</module>
</application>

    
Above application.xml file describe the content of example2.ear. Tag <web-uri>example2.war</web-uri> describe the name of web module (i.e.. example2.war) packaged in the archive. The context root of this example2.ear is eample2.
Writing Ant build xml file
To build example2.ear file, I have written build.xml which compiles source code and builds deployable archive file.
build.xml file:
 <?xml version="1.0"?>
<!-- ==================================================== -->
<!-- Build file for our first web application -->
<!-- build.xml, Sunday, July 07, 2002 -->
<!-- Author: Deepak Kumar -->
<!-- Email : deepak@roseindia.net -->
<!-- Url : http://www.roseindia.net -->
<!-- ==================================================== -->


<project name="Jboss 3.0 tutorial series" default="all" basedir=".">


<target name="init">
<property name="dirs.base" value="${basedir}"/>
<property name="classdir" value="${dirs.base}/build/src"/>
<property name="src" value="${dirs.base}/src"/>
<property name="web" value="${dirs.base}/web"/>
<property name="deploymentdescription" value="${dirs.base}/build/deploymentdescriptors"/>

<property name="warFile" value="example2.war"/>
<property name="earFile" value="example2.ear"/>


<property name="earDir" value="${dirs.base}/build/ear"/>
<property name="warDir" value="${dirs.base}/build/war"/>


<!-- Create Web-inf and classes directories -->
<mkdir dir="${warDir}/WEB-INF"/>
<mkdir dir="${warDir}/WEB-INF/classes"/>

<!-- Create Meta-inf and classes directories -->
<mkdir dir="${earDir}/META-INF"/>

</target>

<!-- Main target -->
<target name="all" depends="init,build,buildWar,buildEar"/>


<!-- Compile Java Files and store in /build/src directory -->
<target name="build" >
<javac srcdir="${src}" destdir="${classdir}" debug="true" includes="**/*.java" />
</target>

<!-- Create the War File -->
<target name="buildWar" depends="init">
<copy todir="${warDir}/WEB-INF/classes">
<fileset dir="${classdir}" includes="**/*.class" />
</copy>

<copy todir="${warDir}/WEB-INF">
<fileset dir="${deploymentdescription}" includes="web.xml" />
</copy>

<copy todir="${warDir}">
<fileset dir="${web}" includes="**/*.*" />
</copy>

<!-- Create war file and place in ear directory -->
<jar jarfile="${earDir}/${warFile}" basedir="${warDir}" />


</target>


<!-- Create the War File -->
<target name="buildEar" depends="init">
<copy todir="${earDir}/META-INF">
<fileset dir="${deploymentdescription}" includes="application.xml" />
</copy>

<!-- Create ear file and place in ear directory -->
<jar jarfile="${dirs.base}/${earFile}" basedir="${earDir}" />
</target>

</project>

 
Above build.xml file is design to create example2.ear for us in the base directory.
Running Ant utility to build example2.ear
Now it's time to build example2.ear and deploy on the Jboss 3.0 application server.
To execute Ant utility go to c:\anttest\example2 directory and issue ant command.
Out put of ant command:
C:\anttest\example2>ant
Buildfile: build.xml

init:
[mkdir] Created dir: C:\anttest\example2\build\war\WEB-INF
[mkdir] Created dir: C:\anttest\example2\build\war\WEB-INF\classes
[mkdir] Created dir: C:\anttest\example2\build\ear\META-INF

build:
[javac] Compiling 1 source file to C:\anttest\example2\build\src

buildWar:
[copy] Copying 1 file to C:\anttest\example2\build\war\WEB-INF\classes
[copy] Copying 1 file to C:\anttest\example2\build\war\WEB-INF
[copy] Copying 1 file to C:\anttest\example2\build\war
[jar] Building jar: C:\anttest\example2\build\ear\example2.war

buildEar:
[copy] Copying 1 file to C:\anttest\example2\build\ear\META-INF
[jar] Building jar: C:\anttest\example2\example2.ear

all:

BUILD SUCCESSFUL

Total time: 8 seconds
C:\anttest\example2>|
The above process will create example2.ear in c:\anttest\example2 directory.
Deploying and testing J2EE application
Statrt Jboss 3.0 and copy example2.ear file into the JBOSS_HOME/server/default/deploy directory. Jboss application server automatically deploys the application. Open web browse and type http://localhost:8080/example2 in the web browser. Browse should show the screen something like this:

Also try to execute Hello World Servlet by clicking "Click Here to" link on the index.jsp in the browser.
In this lesson you learned how to write build.xml file to automate the process of .ear file creation. Ant utility with help of our build.xml file automatically compiles source code and assembles J2EE application for us. Ant utility is very power full and it reduces the development time significantly.

Configure web logic server in myeclipse



Image

Download & Configure Oracle OC4J Server for Netbeans IDE

Are you using Oracle OC4J server? If you're, did you think about using the Netbeans IDE (Integrated Development Environment)?

Download OC4J from the Netbeans updates
Open Netbeans IDE and then follow below steps to configure the OC4J server.
1. Tools > Update Center
2. Select "Netbeans Update Center Beta"
3. Select OC4J 10g

You can then configure a new server and run/stop the server from your IDE.

You can get more info from official website for Netbeans OC4J module @ Netbeans OC4J module.

Java program to fetch and sort files from a directory

Hi - Have you worked with Java file system objects? It has very good features like accessing files and sorting them in ascending order and descending order. In Java 1.5, Sun Microsystem has introduced the Comparator class to make the sort operations easier. So, I'm going to discuss about this today.

When you create a File object, it will just create a reference for the path that you've given for the constructor. You can invoke methods like exists() to find whether the file exists or isDirectory() to find whether this file represents a directory on the disk etc.

Here is the sample program to to access files and order them by ascending order based on name, last modified date, and size. It explains about file filter as well.

SortFiles.java
package filesdemo;

import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
import java.util.Comparator;

/**
 * A demo class to show the file sorting techniques.
 * @author Santhosh Reddy Mandadi
 * @since 05-Mar-2010
 * @version 1.0
 */
public class SortFiles
{
  public static void main(String[] args)
  {
    File dir = new File("C:\\");
    if(dir.isDirectory())
    {
      // Fetching the list from the directory
      File[] files = dir.listFiles();

      //Prints all the files and folders exists under dir
      for(File file:files)
      {
        System.out.println(file.getName());
      }
      System.out.println("All the files including folders");
      System.out.println("--------------------------------");
      
      // Creating a filter to return only files.
      FileFilter fileFilter = new FileFilter()
      {
        @Override
        public boolean accept(File file) {
          return !file.isDirectory();
        }
      };
      files = dir.listFiles(fileFilter);

      //Lists only files since we've applied file filter
      for(File file:files)
      {
        System.out.println(file.getName());
      }
      System.out.println("After filtering the folders");
      System.out.println("--------------------------------");

      // Sort files by name
      Arrays.sort(files, new Comparator()
      {
        @Override
        public int compare(Object f1, Object f2) {
          return ((File) f1).getName().compareTo(((File) f2).getName());
        }
      });

      //Prints the files in file name ascending order
      for(File file:files)
      {
        System.out.println(file.getName());
      }
      System.out.println("After sorting by name");
      System.out.println("----------------------------------");

      // Sort files by size.
      Arrays.sort(files, new Comparator()
      {
        @Override
        public int compare(Object f1, Object f2)
        {
          if (((File) f1).length() < ((File) f2).length())
          {
            return -1;
          }
          else if (((File) f1).length() > ((File) f2).length())
          {
            return 1;
          }
          else
          {
            return 0;
          }
        }
      });

      //Prints files in order by file size
      for(File file:files)
      {
        System.out.println(file.getName());
      }
      System.out.println("After sorting by length");
      System.out.println("-------------------------------");

      // Sort files by date.
      Arrays.sort(files, new Comparator()
      {
        @Override
        public int compare(Object f1, Object f2)
        {
          if (((File) f1).lastModified() < ((File) f2).lastModified())
          {
            return -1;
          }
          else if (((File) f1).lastModified() > ((File) f2).lastModified())
          {
            return 1;
          }
          else
          {
            return 0;
          }
        }
      });

      //Prints files in order by last modified date
      for(File file:files)
      {
        System.out.println(file.getName());
      }
      System.out.println("-------------------------");
    }
  }
}


Above program has been tested in 1.5 and 1.6.

Click here to check out other programs that I've developed.

System.out.println() short cut keys on different IDEs

If you're using different IDE to develop a program in Java, you might have searched for a short cut key for System.out.println(). I've so far programmed Java using 3 different IDEs Netbeans, Eclipse, and JDeveloper.

Here the short cuts for System.out.println on each IDE above
Short cut on Netbeans
Type sout and press tab key

Short cut on Eclipse
Type syso and press Ctrl+space

Short cut on JDeveloper
Type sop and press Alt+Enter