Sunday, 20 January 2013

Java Web Application using Eclipse

Java's web technology provides us the facility to create dynamic web applications easily with the components it provide. Servlets play an important role in Java web application development by providing the developer with its options to hold the client request, pass it to the handled method and send the response to the client. This document will help you in understanding the architecture better.

Before starting web development, the developer should understand the request flow. All requests from the client (web browser) to server happens through HTTP methods defined by the protocol. GET and POST are the methods which are commonly used to pass the request. Each request contains an action and may have parameters sent to the server to perform specific operation. For example, in a login operation, the action would be loginaction and the parameters passed can be user-name and password.

Once the server processes the request, it responds back to the client with a status code saying if the operation was successful, a content type which helps browsers to show the response as html, pdf, zip etc. and optional message body.

Another important matter to be noticed is that the Java Server Pages (JSP) should be thought only in the scope of web server. The contents of the JSPs will get transformed to html elements before being served to the browser as response.

Moreover, web.xml, residing in the WEB-INF folder is the major configuration file. You will come across this file as we go forward.

Here we start developing a hello world web application using Eclipse. Assuming that you have configured a web server on your Eclipse IDE. If you have not, you can follow this link to configure JBoss web server.

This Eclipse project can be downloaded here. You can extract the file and use File > Import to download the project into your Eclipse workspace.

  1. On Eclipse, go to File > New > Project.
  2. Under Web, choose Dynamic Web Project and choose Next.
  3. Name your project and click Next.
  4. Click Next, choose your context root and content directory, and then click Finish. Context root is what you will use to access the application from a browser client. Content directory is where you will create your web pages and other resources such as images and javascript files.

    We have successfully created a web project. Next is to write a Servlet to handle requests.
  5. Right-click on the project, choose New > Servlet.
  6. Name the package, then the Servlet and click Next.
  7. Type any description, edit the default URL mapping and click Next.
  8. Choose the methods to handle the types of requests and click Finish.

    If you look into web.xml contents, you will find that the Servlet which we created is mapped to the URL we had provided in the above step. Whatever requests arrives to the application in the url-pattern we have specified will be set to be handled by the mapped Servlet instance. Our Servlet extends from HttpServlet. Go through the javadoc of HttpServlet and GenericServlet to find the basic methods and their descriptions. I have chosen to get hold of service, init and destroy methods just to print the life-cycle of this Servlet. Hence, the method call will be directed to the super class for actual processing.

  9. In the doGet method, write the code to handle the request.
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      System.out.println("In the doGet(HttpServletRequest request, HttpServletResponse response) method of HelloWorldServlet");
      PrintWriter printWriter = response.getWriter();
      printWriter.print("<html><head></head><body>Hello World</body></html>");
  10. Create a JSP file as referred in web.xml's welcome-file-list. The first available among them will be be displayed by default on visiting the context root. Right-click on the project, choose New > JSP File or from New > Other > Web > JSP File.
  11. Select WebContent folder or the contents folder mentioned in step 4, type the file name and click Next.
  12. By default, the JSP file will be opened in your editor. Modify the title as you wish.
  13. Add the following code snippet in the body part of JSP and save the file.
      Object message = request.getAttribute("message");
      if (message == null) {
     <form action="sayHello" method="post">
      <input type="submit" value="Submit" />
      } else {
  14. Edit the doPost method of Servlet as
     protected void doPost(HttpServletRequest request,
       HttpServletResponse response) throws ServletException, IOException {
        .println("In the doPost(HttpServletRequest request, HttpServletResponse response) method of HelloWorldServlet");
      request.setAttribute("message", "Hello World through post");
      RequestDispatcher requestDispatcher = getServletContext()
      requestDispatcher.forward(request, response);
  15. Let us try running the application. Right-click on the application and choose Run As > Run On Server and click Finish.
  16. On your browser, go to http://<server-host-name>:<port>/<contextpath>. In my case http://localhost:8080/MyHelloWorldWeb.
  17. You will see a Submit button because web.xml is blindly set to show the welcome file. The content of the file tries to get the request attribute named message, which will be null since the request has not gone to the doPost method.
  18. Click on the Submit button and see the server log on the console. The doPost method would be called and message will be passed to index.jsp, which behaves in a different way.
  19. Try the URL contextpath/sayHello and check the log to see the request being handled by doGet method.
  20. From the Servers view of Eclipse, expand the server, right click on the web application and say Remove.
  21. Look at the console to see the message given to print at destroy method being called which completes the life-cycle of the Servlet.

Configuring JBoss server on Eclipse

JBoss application server is a server which offers Java Enterprise Edition services to web applications authored in Java language.

Here are the steps to configure JBoss server on Eclipse:

  1. Download JBoss server from here. I have chosen the 4.2.3 version of JBoss server to download.
  2. Extract the downloaded compressed file to a suitable location. I have extracted the file to /opt.
  3. On Eclipse, go to Servers view. If you do not see Servers view, go to Window > Show View > OtherOn the Show View window, choose Server > Servers and click OK.
  4. Click on new server wizard or right-click and choose New > Server.
  5. Choose JBoss > JBoss v4.2 and click Next.
  6. To set the Application Server Directory, click Browse or type the path to the extracted server folder in step 2 and click Next.
  7. Choose address, port, JNDI port and server configuration and click Next. I have left it as default values here.
  8. If you have any web application to be set to run on the server, add them and click Finish. You will find the server being listed in the Servers view.
  9. Double click on the server listed in the Servers view or right-click and choose Open.
  10. The server can be configured in the window opened up. Expand the Timeouts section and modify the Start and Stop values. These are the values in which the server has to start-up or shutdown as monitored by Eclipse. You may need to increase these timings, otherwise you will end up with an error saying server could not be started as displayed below. Once done, save the configuration from File > Save.

  11. Right-click on the server from Servers view and choose Start.
  12. Monitor the Console view to see if the server has started successfully.
  13. Test the server from browser by going to the host name and port configured.

Saturday, 19 January 2013

Java standalone application on Eclipse

Java standalone application would be the easiest one to start when learning the language. We will print "Hello World" text on the console as the first step.

Java standalone applications should have at least a class with main method, in the right signature. This is the first method that will take the handle of the application when called by Java Virtual Machine. Here we go.

  1. On your Eclipse IDE, click on File > New > Project.
  2. Choose Java > Java Project and click Next.
  3. Key in the project name and click Finish.
  4. From the Package Explorer, right click and create new Class.
  5. Name your new Class. If you need to place the new Class in a package, fill-in the package name. Since this is your Main class, you can check "public static void main(String[] args)" under "Which method stubs would you like to create?". I would not select this option now.
  6. You will find your Main class being opened in the editor. You can type the entire signature of the main method or just type main, then use Ctrl + Space to show the proposed templates and choose main method to generate the main method.
  7. Type the statement to print "Hello World" statement on the output stream. That is, System.out.println("Hello World");. The template way to type the statement is sysout and using Ctrl + Space.
  8. Format the code snippet using Source > Format or Ctrl + Shift + F and save the file.
  9. Right-click on the project or the class and use Run As > Java Application to run the file.
  10. See the console. If console could not be found, select to show it from Window menu.