Chapter 1

Getting Started

The wise developer uses an integrated development environment (IDE), and the web developer is by no means an exception. An IDE is a tool that allows you to work faster and more productively. Luckily for Java developers, there are a couple of superior IDEs that come at no cost. Eclipse EE and NetBeans are some of them. Both are excellent products but NetBeans is a one-stop shop, unlike Eclipse, which sometimes require you to install plug-ins. It is not surprising then that many beginners and seasoned programmers choose NetBeans as their main Java IDE. All examples in this book have also been developed using NetBeans.

This chapter shows you how to choose the suitable NetBeans bundle, install it and create your first servlet application. All these in less than fifteen minutes.

Downloading and Installing NetBeans

NetBeans is written in Java and, as such, can run on any platform where Java is available. Sun Microsystems launched the NetBeans open source project in 2000. The name NetBeans came from Netbeans Ceska Republika, a Czech company that Sun bought over. The new project was based on the code Sun acquired as the result of the purchase.

You can download NetBeans free of charge from this website:

http://netbeans.org/downloads

The latest version of NetBeans at the time of writing is 8.0.2, even though version 8.1 is coming soon. Netbeans ships in five download bundles, and to develop servlet/JSP applications you need the Java EE bundle.

If you already have a Java SE bundle installed, uninstall it before installing the Java EE bundle. From experience, installing the Java EE bundle on top of the Java SE bundle may cause JSP page rendering to not work properly.

Note

NetBeans 8 requires JDK 7 or later. I assume you have JDK 7 or later installed on your computer. If not, install it before you install NetBeans.

Here are the steps to install the NetBeans Java EE bundle.

1. On Windows, double-click the installer (the .exe file). On Mac OS X, run the installer (the .dmg file) and on the panel that opens double-click the package icon. On Linux, run these commands:

      $ chmod +x installer-file-name
      $ ./installer-file-name

The installation wizard will launch. Figure 1.1 shows the first window of the installation wizard. It asks you if you want to install GlassFish and Tomcat. By default, only GlassFish will be installed. However, check the “Apache Tomcat 8.0.15” check box too so you can use Tomcat to run your applications later.

Figure 1.1: Selecting servers to install

2. Click Next. You will see a license agreement, as shown in Figure 1.2.

Figure 1.2: Accepting the NetBeans license agreement

3. Click the “I accept the terms in the license agreement” check box and then click Next. You will see the License agreement for Junit (See Figure 1.3). It is a good idea to install JUnit, unless you have space constraint.

Figure 1.3: JUnit license agreement

4. Click Next again. The next window, shown in Figure 1.4, prompts you for an installation directory. Also, make sure the installer can find the JDK. Most of the time, Netbeans will be able to find the JDK. If not, browse to the location of the JDK installed on your local machine.

Figure 1.4: Selecting the installation folder

5. Click Next. The next window asks you to choose an installation folder for GlassFish.

Figure 1.5: Choosing the installation folder for Glassfish

Most of the time, Netbeans will be able to find the JDK. If not, browse to the location of the JDK on your local machine.

6. Click Next. In the next window, shown in Figure 1.6, you will be prompted to select an installation directory for Tomcat.

Figure 1.6: Selecting the installation directory for Tomcat

7. Click Next for the last time. Figure 1.7 shows a window that summarizes what components will be installed.

Figure 1.7: Confirming installation directories

8. As the last step, click Install. It will take a while, depending on your computer speed and whether you are installing to an SSD or HDD drive. When it’s finally done, you’ll see a window similar to that in Figure 1.8.

Figure 1.8: Installation complete

9. Click Finish. Figure 1.9 shows the welcome page.

Figure 1.9: NetBeans’ welcome page

Voilà, you are now ready to create your first servlet application.

Creating A Web Project with NetBeans

Creating a web project with NetBeans involves a couple mouse clicks and entering a project name and a context path. Follow these steps to create a web project. It assumes NetBeans is already running.

1. Click the File menu and select New Project. The New Project dialog will open. This is shown in Figure 1.10.

Figure 1.10: Selecting Project type

2. NetBeans offers many types of applications, including a Java console application, JavaFX application, Java Web and Java EE application. To create a servlet application, select Java Web from the Categories window and click Web Application from the Projects window. Note also that the left window shows the step you are at. Now it is time to click the Next button. The New Web Application window, shown in Figure 1.11, opens.

Figure 1.11: The New Web Application window

3. In the New Web Application window you need to enter a project name and select a project location. The project location is a folder that will contain all your project resources. Type in getstarted as the project name and browse to a folder in your local system. After that, click Next. You will see the next wizard of the New Web Application window.

Figure 1.12: Selecting a server

3. Now, select a server that will be used to run your new application. It is either Tomcat or GlassFish, both madly loved by Java developers. For this exercise, though, select Apache Tomcat from the Server dropdown and click Next again.

Figure 1.13: Select a framework

4. The next wizard, shown in Figure 1.13, wants you to select a framework. It is a good idea to use a web framework such as Spring MVC or JavaServer Faces and I will show how to do that in the last chapters of this book. For now, though, select none and click Finish.

That’s it. You just created a web project. You will now see the NetBeans project window showing a project named getstarted. See Figure 1.14 for details.

Figure 1.14: A web project called getstarted

By default, NetBeans creates a project structure containing several folders and an HTML page named index.html. NetBeans will also open the HTML file in one of the many editors it has. You’re very close.

To run the application, right click on the getstarted project icon in the Project pane and click Run. Netbeans will launch your default browser and direct it to this URL:

http://localhost:8080/getstarted/

This effectively invokes the default resource in your application, which in this case is the index.html file. Figure 1.15 shows the index.html page in my default browser.

Figure 1.15: The default page of the getstarted application

Note that by default Tomcat and GlassFish run on port 8080. If another application is already running on this port, Tomcat or GlassFish will fail to launch. If this happens to you, close the offending application and run the application again.

Troubleshooting

NetBeans is a superb product, but it is not perfect. On Windows, with Netbeans 7 and 8, Netbeans might fail to start Tomcat. If you encounter this, here is a solution.

1. Go to the bin directory of the Tomcat installation

2. Open the catalina.bat file with Notepad or another text editor.

3. Locate these two lines:

      :noJuliConfig
      set "JAVA_OPTS=%JAVA_OPTS% %LOGGING_CONFIG%"

4. Remove the double quotes surrounding the JAVA_OPTS variable.

5. Locate these two lines:

      :noJuliManager
      set "JAVA_OPTS=%JAVA_OPTS% %LOGGING_MANAGER%"

6. Again, remove the double quotes surrounding the JAVA_OPTS variable.

7. Save the catalina.bat file.

8. Run the application again from within Netbeans.

Creating A Servlet

When you create a web project with NetBeans, it does not actually creates a servlet, because it does not know you want one. However, do not be disappointed. It is easy to create one.

1. Right click on the getstarted project icon and select New > Servlet. You will see the New Servlet window like the one in Figure 1.16.

Figure 1.16: Entering a class name and package

2. Enter WelcomeServlet as the class name. By convention a servlet class name ends with Servlet and it is a good idea to follow this convention. In addition, the package name for the servlet class should not be left blank. In this case, I am using getstarted.

3. Click Next. The New Servlet window will show a new wizard.

Figure 1.17: Configuring the servlet

4. In the next wizard, you are asked to name the servlet as well as specify a URI to invoke the servlet. By default the class name will be used as the URI pattern. However, I do not think you should accept this URI pattern. This URI will probably be used by users of your application. To the non-technical user, Servlet means nothing and can be confusing. As such, I changed the URI pattern to /welcome, as shown in Figure 1.17.

  • 5. Click Finish to complete the process.

As soon as you click the Finish button, NetBeans will create a servlet class according to what you specified in the New Servlet window. Figure 1.18 shows the servlet code.

Figure 1.18: The created servlet class

For clarity, the servlet class is printed in Listing 1.1.

Listing 1.1: The servlet class

package getstarted;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "WelcomeServlet", urlPatterns = {"/welcome"})
public class WelcomeServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and 
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, 
            HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample 
               code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet WelcomeServlet</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet WelcomeServlet at " + 
                    request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        }
    }

    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }
}

I explain the servlet class in Chapter 1, “The Servlet API.” For now, make sure that you can run this servlet.

To invoke the servlet, right-click on the servlet class in the Projects window and select Run File. Alternatively, simply type this URL in your browser, assuming, of course, Tomcat is already running.

http://localhost:8080/getstarted/welcome

Figure 1.19 shows the servlet rendering in your browser.

Figure 1.19: The Welcome servlet

The wonderful thing about using Tomcat with NetBeans is if you edit your servlet, Tomcat will reload your application automatically. However, it will sometimes fail and you will have to restart Tomcat manually. The next section tells you how to do it.

Behind the Scenes

You must be curious to know how NetBeans does its magic. How does it make everything so easy?

When you run a web application from NetBeans, it does these behind the scenes.

1. It packages the application in a war file, which is basically a zip file. The war file is the official format for deploying a servlet application. Alternatively, if no war file is needed by the servlet container, NetBeans organizes the application in a specific directory structure.

2. It launches a servlet container, such as Tomcat or GlassFish if none is already running.

3. It registers the web package with the servlet container, effectively loading the web application and running it on the servlet container.

4. It launches the default browser and directs it to the default URL.

Step 1 is of interest because when you finish developing and are ready to deploy the application in an environment where there is no NetBeans installed, you have to package the application into a war file and give the war file to the person in charge of the production server.

Deployment will be discussed in further detail in Chapter 20, “Deployment.” For now, it is important that I pique your interest in the directory structure of a servlet application. Take a look at the Figure 1.20 that shows the directory structure of the getstarted application. You can find this in the Files tab next to the Projects tab. Find your project and expand the build directory.

Figure 1.20: The directory structure of a servlet application

It is a simple structure. The web directory is the application directory and does not have to be called web. Beneath it is a WEB-INF directory, which must be present. The WEB-INF directory may contain a classes directory that hosts servlet classes and other Java classes. The META-INF directory is optional and may contain a manifest file and server-specific files.

The directory structure may contain other resources and you will learn more of it in the next chapters.

Starting, Stopping and Restarting Tomcat

If for some reason you need to start, stop or restart Tomcat, you can do it from inside NetBeans. Just click the Services tab to the right of the Projects tab in the application window. The Services window is shown in Figure 1.21.

Figure 1.21: The Services window

Among other things, you will see a Servers node. Click on the node and you will see the list of servers available from inside NetBeans. Right click on a server to stop, start or restart the server.

Alternatively, a shortcut is available from the Output window. Figure 1.22 shows the Output window for the running server. Pay attention to the five button on the left hand side. The red square button is the Stop button and the one on top is the Start button. Hover your mouse to learn the function of each button.

Figure 1.22: Starting and Stopping the server from the Output window

If you don’t see the Output window, click Output from the Window menu.

Note

When you close NetBeans, it also stops any running server.

Monitoring HTTP Traffic

As your application grows more complex, you might need to monitor the HTTP traffic between your application and the browser. The best tool for this purpose is probably the Chrome Developer Tools (DevTools for short) that ship with the Google Chrome browser. In fact, monitoring HTTP tranffic is just one of the many features it offers.

To launch the DevTools and start monitoring HTTP traffic, follow these steps.

1. Press F12 to display the DevTools.

2. Click on the Network tab in the DevTools.

3. Refresh the page. A name path will appear on the tool pane.

4. Click on the name path (in this example, welcome/getstarted). It will show the HTTP request and response for the request. (See Figure 1.23.)

Figure 1.23: Monitoring HTTP traffic with Chrome’s Developer Tool

More information about these amazing tools can be found here:

https://developer.chrome.com/devtools

Summary

An IDE is a developer’s best friend. You should always use one in every circumstance. NetBeans and Eclipse are free IDE’s and great products. Choosing an IDE is sometimes a matter of taste and sometimes an inexplicable company policy. This chapter showed you how to use NetBeans to develop a Java web application and add a servlet to it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.124.244