Section 13.8. Servlets

   

13.8 Servlets

Because ColdFusion is tag-based, and JSP is tag-based for the most part, it is most appropriate to cover JSPs. They are easier to write, deploy, and maintain than servlets. They are capable of everything that servlets are, and they are more familiar to ColdFusion developers. So we will work almost exclusively with them.

However, because eventually every JSP becomes a servlet, and because they continue to be a very important force in the world of J2EE, we should at least introduce them. Here we'll look at a basic "Hello, world" servlet that just prints text to the browser. Then we will look at working with servlet mappings. Finally, because it is such a commonly required task, we'll write a complete application that uses a servlet to authenticate a user against a database and store his or her username in the session object if the login is successful. Because of your background in ColdFusion and what we've learned about Java throughout the book, we'll learn enough about servlets here to go a long way.

Once you grasp the basic concept of servlets and see how to deploy them, it is easy to start writing them. They are easy to write because they are more or less regular Java classes that extend HttpServlet . The main caveat regarding servlets is that they are a very poor choice for outputting presentation layer items; that is, content, graphics, or HTML.

Let us write a servlet now and see if we can't get it to appear in a browser.

First, we create the Tomcat directory structure as specified above. We create an optional directory called src , which we will use to write all of our servlets and Java source files in. Then, we can output the compiled class files into the WEB-INF/classes directory using a setting in our IDE. They can also be compiled directly or moved into the classes directory. This keeps you from having to deploy all of your source files along with the rest of your application.

13.8.1 TestServlet

 /* File: Hello.java   * Purpose: demonstrate use and deployment of  * servlets  */ import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class Hello extends HttpServlet {     public void doGet(HttpServletRequest request,                         HttpServletResponse response)                 throws ServletException, IOException {         // if this is an HTTP GET request, forward         // it in effect to doPost(). They will just         // do the same thing         doPost(request, response);     }     public void doPost(HttpServletRequest request,                        HttpServletResponse response)                 throws ServletException, IOException {         // make a string representing the user passed         String user = request.getParameter("user");         // if no user is specified, this value will be used         if (request.getParameter("user") == null) {             user = "world";         }         // set the content type         // this will be ignored if included         // in another servlet or JSP         response.setContentType("text/html");         // get an out stream so we can print to the         // browser         PrintWriter out = response.getWriter();         out.println("<HTML><BODY>");         out.println("<h1>Hello, " + user + "!</h1>");         out.println("</BODY></HTML>");     } } // eof 

Note

It is not necessary to add all of your servlets to the web.xml file. You only need to add servlets to this file for two chief reasons: to specify initialization parameters for those servlets that require additional information and to provide alternate URL mappings for your servlets.


Now restart Tomcat, and in your browser call this URL: http://localhost:8080/javaforcf/servlet/Hello .

Because no parameter was specified, the output is:

 Hello, world! 

If you now call this address, http://localhost:8080/javaforcf/servlet/Hello?user=kitty , you will see your parameter used in the output instead:

 Hello, kitty! 

Servlets do not require any file extension for the same reason that you do not need to specify one when executing a desktop Java application at the command line using the java command.

13.8.2 Servlet Mappings and Custom URLs

You will likely have noticed that we reference "servlet" in the URL, despite the fact that there is no directory named servlet under our classes directory where we placed the class file. This is a virtual mapping built into the container that allows you to execute any servlet without having to add an entry to the web.xml file.

Examine the following code:

 <servlet>     <servlet-name>MyServlet</servlet-name>    <display-name>A Test Servlet</display-name>    <description>Says hello</description>    <servlet-class>packagename.classname</servlet-class> </servlet> <servlet-mapping>    <servlet-name>MyServlet</servlet-name>    <url-pattern>*.do</url-pattern> </servlet-mapping> 

Using these elements, we can create a new entry in the web.xml file that states the name of the servlet, a description and display name (which are arbitary text), and then a class that makes up that servlet. You can optionally include a <servlet-mapping> element, which says, "every time you come across this particular pattern in a URL request made of this server, execute the servlet with this name." So using this entry above, we make the MyServlet servlet execute every time we encounter a URL containing any text that ends in .do , which is a somewhat common practice.

In the next section, we'll make a complete database-driven authentication servlet, which will demonstrate many of the fundamental things we should know about servlets before moving into JSPs.


   
Top


Java for ColdFusion Developers
Java for ColdFusion Developers
ISBN: 0130461806
EAN: 2147483647
Year: 2005
Pages: 206
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net