Showing posts with label application. Show all posts
Showing posts with label application. Show all posts

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");
      response.setContentType("text/html");
      PrintWriter printWriter = response.getWriter();
      printWriter.print("<html><head></head><body>Hello World</body></html>");
      printWriter.close();
     }
  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.
    <body>
     <%
      Object message = request.getAttribute("message");
      if (message == null) {
     %>
     <form action="sayHello" method="post">
      <input type="submit" value="Submit" />
     </form>
     <%
      } else {
     %>
     <%=message%>
     <%
      }
     %>
    </body>
    
  14. Edit the doPost method of Servlet as
     protected void doPost(HttpServletRequest request,
       HttpServletResponse response) throws ServletException, IOException {
      System.out
        .println("In the doPost(HttpServletRequest request, HttpServletResponse response) method of HelloWorldServlet");
      request.setAttribute("message", "Hello World through post");
      RequestDispatcher requestDispatcher = getServletContext()
        .getRequestDispatcher("/index.jsp");
      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.

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.