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.

4 comments:

  1. awesome,nice and informative blog.Thanks to sharing this blog.seo

    ReplyDelete
  2. no not in the least Flash isn't in a similar play ground as Javascipt is and we will investigate what that implies as we investigate a customized point of view of web/dev history.
    Java

    ReplyDelete
  3. IT professionals working in this field typically learn about IT risk, application layer attacks, website penetration testing, web security via web application security training courses.
    web development service

    ReplyDelete
  4. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    Java Online Training Java Training in Chennai

    ReplyDelete