It's a normal servlet, I tell ya
Creating the servlet is a no-brainer. You've done it hundreds of times. Implement your service methods (doGet/doPost) and whatever business logic you require. Under normal circumstances, you will want to return an XML document to the caller, but you can return any textual information to the client. Let's look at the provided servlet code to understand where the data is coming from for the Ajax calls.
- Under the Project Explorer, expand the tree down to the code for the servlet. The file is called com.ibm.examples.Ajax.servlets > DBExplorerServlet.java. Double click this Java file to open it in the editor.
- Notice the doPost() method of the servlet and what it accomplishes. This particular code is not Ajax specific, but it is one way of getting a servlet to respond to the request by using parameters sent by the XMLHttpRequest object explained later in the exercise.
- Feel free to browse the code if you want to have a better understanding of what it does.
- Enter the following URL into your browser window. An example is
shown in Figure 8.
Figure 8. Results of calling the servlet directly
Note: You need to adjust the actual URL to match your deployment. The
/wps/PA_dsllabuportion of our sample URL is defined by the portal when you deployed your portlet application the first time. To see the context of your portal, look at the top of the Ajax portlet we deployed earlier.
The only real trick when bundling a servlet with a portlet application is registering it into the web.xml file. You do this exactly as you would in a normal Web application.
Below is a fragment of the web.xml file from our exercise. The
important item to notice is the Servlet-mapping >
url-pattern. In this case, it's
/DBExplorerServlet. This value is used when
communicate with the servlet. Go ahead and view the Deployment
Descriptor of our project. A sample is shown in Figure 9.
Figure 9. Portlet web.xml file with bundled servlet definition