Welcome!

Eclipse Authors: Pat Romanski, Elizabeth White, Liz McMillan, David H Deans, JP Morgenthal

Related Topics: Eclipse

Eclipse: Article

Creating Web Applications with the Eclipse Web Tools Project

Using open source to develop Web applications, EJBs, and Web services

Creating Servlets and JSPs
The Model-View-Controller (MVC) paradigm requires the implementation of three loosely coupled tiers in the application:

  • Model: Business logic and domain objects of the application
  • View: Presentation, user interface
  • Controller: Something that sits between the model and view, allowing them to interact in a loosely coupled manner, meaning that the model does not have to be aware of the view, and a different view could possibly be used with the same model.

So far we have implemented only Model - domain objects and command classes. Controller will be implemented as a servlet and View will be implemented as JSPs.

Web Tools provides comprehensive wizards and editors for creating servlets and JSPs. We'll start by creating a package called "servlet" in our Eclipse project where all our servlets will reside. Next, we'll launch the wizard for creating a CreateCustomerServlet by selecting File-New-Other, and then Web-Servlet (see Figure 4).

On the screen in Figure 4, we can specify the Web Project and package where servlet should reside, and the next screen will look like Figure 5.

On this one, we can specify the optional description for the servlet, initialization parameters (that can be retrieved by the servlet in the init() method from its ServletConfig object), and URL mapping. Figure 6 shows the final screen for defining servlet.

At this point, we are presented with the capability to specify the interfaces that this servlet will implement (by default, all the servlets implement the javax.servlet.Servlet interface), and the methods that should be automatically generated when the servlet is created.

Just click on Finish and the servlet is generated. This also creates the following entry in the web.xml file:


<servlet>
<description>Create Customers
Servlet</description>
<display-name>ListCustomers</display-name>
<servlet-name>ListCustomers</servlet-name>
<servlet-class>servlet.ListCustomersServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ListCustomers</servlet-name>
<url-pattern>/ListCustomers</url-pat-tern>
</servlet-mapping>

Another thing that must be added to web.xml is the resource reference to the datasource that has been configured in DBTest.xml:


<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

This XML is necessary for the CommandExecutor datasource lookup code to work properly.

In the init() method of ListCustomers-Servlet, we will get the instance of the CommandExecutor (see Listing 8), which will retrieve the data source and cache it for future use to supply database connections. It's a good practice to cache a reference to JNDI data source, because retrieving it is a time-consuming operation.

In the doGet() method (see Listing 9), we will execute the database command and forward the list of registered customers to the JSP to display them.

In this doGet method, request attribute "customers" is set to the generic ArrayList and then RequestDispatcher object is used to forward a response to customers.jsp (see Listing 10).

Using some of the new features of J2SE 5.0 such as generics and enhanced "for" loop improves the JSP code by reducing the amount of Java code in it. Creating and editing JSP using WTP is simple. Select the Web content folder of your Web project, right-click, and select New - Other from the menu. From the dialog that appears, select Web - JSP, then specify the name of the JSP you want to create. WTP also allows you to select an existing template for your JSP to be based on. Three built-in templates are provided based on HTML, XHTML, and XML.

In a similar way, we can create other servlets and JSP pages in our application (see the source code), which is easy to import into Eclipse by using its File-Import menu. Figure 7 shows the Web site map of our simple Web application. As you can see, users initially get to index.html page from which they can perform all the other tasks, such as creating customers and orders, and listing existing customers and their orders.

Debugging Application in Eclipse with WPT
The debugging application in Tomcat involves launching the server in the debug mode. To do this, simply right-click on the Tomcat server and select "Debug." To debug some particular line of code, insert a breakpoint at the line shown in Figure 8.

The server currently running in the debug mode will be automatically selected. After a couple of clicks, the embedded browser page should appear. From now on you can debug the Web application the same way as a regular Java program.

Deploying the Application to Tomcat
Once the application has been tested, it may be ready to deploy. To deploy a Web application, first export it as a WAR file. Simply select File - Export - WAR file.

On the popup window you can check "Export source files" and "Overwrite existing file" if you wish to have your source contained within your WAR file (it may not be a good idea in production) and want to suppress a warning if the file with the same name (perhaps a previously exported version) already exists in the directory and you want to simply overwrite it.

Once the WAR file is exported, deploying it to Tomcat can be done through the Tomcat 5.0 administrative console, which in our case is located at http://localhost:8080/manager/html.

The console displays currently deployed applications and allows you to deploy new, undeploy, and reload existing applications.

Once deployed, we need to make sure that our DBTest.xml file is still there under $TOMCAT\conf\catalina\localhost with all the correct datasource definitions. If it's not, replace it with the correct one that have been saved by you before.

Now, our application is ready to run, so point your browser at http://localhost:8080/DBTest/.

Figure 9 shows what the list of orders for a registered customer will look like.

Summary
I've discussed the development, debugging, and deployment of the Web-based database application using J2SE 5.0, Eclipse Web Tools, the Tomcat application server, and the MySQL database. WTP is still in its beta release, so some of its wizards and capabilities may pose problems; however, we were able to successfully debug and deploy the Web application.

More Stories By Boris Minkin

Boris Minkin is a Senior Technical Architect of a major financial corporation. He has more than 15 years of experience working in various areas of information technology and financial services. Boris is currently pursuing his Masters degree at Stevens Institute of Technology, New Jersey. His professional interests are in the Internet technology, service-oriented architecture, enterprise application architecture, multi-platform distributed applications, and relational database design. You can contact Boris at [email protected]

Comments (15) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Mintara 12/26/07 04:11:21 PM EST

Hello Sir,
Could you please elaborate (for e.g the classes ..I could not find the source code)what you have explained.
Thank you.

Serge Cambour 09/25/07 06:38:15 AM EDT

It would be really a very good article or a tutorial if the author had tested it himself before posting it. I don't even talk of missing details, classes, code mistakes, ets. that make you loose any wish to continue.

Keith Freeman 07/15/06 10:32:01 PM EDT

Well, this seems like a fantastic tutorial, until suddenly the "CreateCustomerServlet" description morphs into a "ListCustomersServlet". We're left to figure out how to finish the servlets ourselves (still in progress for me), since as others point out here a bunch of code is missing from the zip file download. VERY disappointing after such a strong start.

David Paules 05/24/06 04:04:22 PM EDT

Good introduction article. Unfortunately, it's not clear where the database connection file DBTest.xml should reside when running Tomcat under Eclipse. Where does this file or it's content go in the Dynamic Web project tree? Because of this, I get an error message at debug time:

javax.servlet.ServletException: Cannot create JDBC driver of class '' for connect URL 'null'

Chuck Ferrick 05/20/06 09:24:58 PM EDT

I was very interesting article, but most of the listings where not posted. I was hoping to gain some insight on how you configure Hibernate. Your article stated to look at listing 9, but listing 9 was know where to be found. I was also frustrated when I could not find the DBTest.war file on java.sys-con web site.

Good furture article and maybe next time JDJ will include all of the necesasry file listings.

Achille Komla 02/05/06 10:57:41 PM EST

Very well done. It will be good to see how the application works with hibernate.

Daniel Hillebrand 12/15/05 04:35:56 AM EST

Hi Boris,

thank you for your great tutorial! Maybe you could add a note to your article regarding running Tomcat in eclipse:

You have to put the content of DBTest.xml in the (new) file context.xml in "WebContent/META-INF". The path strings are not needed, except the "path" string.

regards, Daniel

Bill Gercken 12/09/05 09:02:38 AM EST

Soource code: For those who did not find it: the link to the source is at the top of listing 1. View link: http://res.sys-con.com/story/nov05/152270/source.html

km 12/07/05 03:41:46 PM EST

could you provide the link for the source code

Paul Mischler 12/05/05 04:39:16 PM EST

Did anyone notice that listings 3-10 aren't included in the dead-tree edition?

Corrections to the article:

For the code to work "out of the box", the Customer and Order classes need to be created in a package called "domain"

Figure 2 shows "cust_id" as a member of the Order class. However, the image of Figure 3 (and the CreateOrder class sample code) utilize "custId".

A helpful reminder that a user with permissions to access the database tables would have been helpful.

CS Cassell 12/02/05 10:01:30 AM EST

Several of the links are broken. This could be a really good article but ones needs the various links to work correctly.

José D´Andrade 12/01/05 09:11:56 AM EST

Please, think Linux. Think about Linux users when writing articles about developing whatever using:

Eclipse
Apache
Tomcat
MySQL

It is confusing to read about things that perhaps only apply to MS Windows (¨be sure to launch C:\Mysql\winmysqladmin.exe ¨) when the tools are mostly used by Linux people. And, this is not religion.

At least, write referencing both OSs.

José D´Andrade 12/01/05 09:10:40 AM EST

Please, think Linux. Think about Linux users when writing articles about developing whatever using:

Eclipse
Apache
Tomcat
MySQL

It is confusing to read about things that perhaps only apply to MS Windows (¨be sure to launch C:\Mysql\winmysqladmin.exe ¨) when the tools are mostly used by Linux people. And, this is not religion.

At least, write referencing both OSs.

Bill Dornbush 11/29/05 03:16:26 PM EST

Where is the source code for the article? I can't find any for this issue of the magazine at java.sys-con.com

IoT & Smart Cities Stories
All in Mobile is a place where we continually maximize their impact by fostering understanding, empathy, insights, creativity and joy. They believe that a truly useful and desirable mobile app doesn't need the brightest idea or the most advanced technology. A great product begins with understanding people. It's easy to think that customers will love your app, but can you justify it? They make sure your final app is something that users truly want and need. The only way to do this is by ...
Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...
DXWorldEXPO LLC announced today that Big Data Federation to Exhibit at the 22nd International CloudEXPO, colocated with DevOpsSUMMIT and DXWorldEXPO, November 12-13, 2018 in New York City. Big Data Federation, Inc. develops and applies artificial intelligence to predict financial and economic events that matter. The company uncovers patterns and precise drivers of performance and outcomes with the aid of machine-learning algorithms, big data, and fundamental analysis. Their products are deployed...
The challenges of aggregating data from consumer-oriented devices, such as wearable technologies and smart thermostats, are fairly well-understood. However, there are a new set of challenges for IoT devices that generate megabytes or gigabytes of data per second. Certainly, the infrastructure will have to change, as those volumes of data will likely overwhelm the available bandwidth for aggregating the data into a central repository. Ochandarena discusses a whole new way to think about your next...
CloudEXPO | DevOpsSUMMIT | DXWorldEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
Cell networks have the advantage of long-range communications, reaching an estimated 90% of the world. But cell networks such as 2G, 3G and LTE consume lots of power and were designed for connecting people. They are not optimized for low- or battery-powered devices or for IoT applications with infrequently transmitted data. Cell IoT modules that support narrow-band IoT and 4G cell networks will enable cell connectivity, device management, and app enablement for low-power wide-area network IoT. B...
The hierarchical architecture that distributes "compute" within the network specially at the edge can enable new services by harnessing emerging technologies. But Edge-Compute comes at increased cost that needs to be managed and potentially augmented by creative architecture solutions as there will always a catching-up with the capacity demands. Processing power in smartphones has enhanced YoY and there is increasingly spare compute capacity that can be potentially pooled. Uber has successfully ...
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...