Wednesday, February 11, 2009

Use Jetty to run Maven web applications in NetBeans

Jetty is a great web server. It is fast to start up and that makes it very useful during development. Jetty has a Maven plugin we can use in our Maven web application project. This way we can use Jetty to test our JSP files. We can change the JSP file and hit the Refresh button of our browser to see the result immediately. We can even compile a Java class file and Jetty will restart so we can test the result in our browser.

Let's see how we can do this in NetBeans. We go to File | New Project, select Maven Project and click the Next button.

In the next dialog window we select Maven Webapp Archetype and click the Next button.

Now we can fill in the values for our project and press the Finish button.

NetBeans creates a new project for us. To add Jetty Maven plugin we must open the pom.xml file for our project. In the build section we must add the following code:


At line 6 we define how often Jetty will scan the source directories to look for changes. Because we add this definition we can change JSP files and see the result in our web browser without restarting the server.

Okay, we have defined Jetty for our project, but how can we run Jetty in NetBeans? We go to File | Project Properties and select the Actions category. We must look for the action Run project and select it. In the Execute goals field we add jetty:run. This will start Jetty if we run our project. We can close the dialog window.

Now we go to Run | Run Project to start Jetty. In the Output window of NetBeans we see the following text:

Starting jetty 6.1.14 ...
2009-02-11 10:20:20.610::INFO:  jetty-6.1.14
2009-02-11 10:20:20.982::INFO:  No Transaction manager found - if your webapp requires one, please configure one.
2009-02-11 10:20:21.335::INFO:  Started SelectChannelConnector@
Started Jetty Server
Starting scanner at interval of 5 seconds.

At line 3 we see Started SelectChannelConnector@ this means Jetty is available at port 8080. We open a web browser and open http://localhost:8080/webappjetty/ and we see the following:

We go back to NetBeans and open the file index.jsp. We add the following to the file:

<h3>It works!</h3>

We switch back to our web browser and reload the page and we get: