Browse in : |
All
> Topics
> Programming
All > Journals > CVu > 124 Any of these categories - All of these categories |
Note: when you create a new publication type, the articles module will automatically use the templates user-display-[publicationtype].xt and user-summary-[publicationtype].xt. If those templates do not exist when you try to preview or display a new article, you'll get this warning :-) Please place your own templates in themes/yourtheme/modules/articles . The templates will get the extension .xt there.
Title: Servlets
Author: Administrator
Date: 03 July 2000 13:15:38 +01:00 or Mon, 03 July 2000 13:15:38 +01:00
Summary:
What is a servlet and why use one?
Body:
A servlet is a piece of Java code that is designed to expand the functionality of a web server in some specific manner - for example interrogating a database and formatting the results into a displayable form.
Servlets are intended to generate dynamic web content. Because they are written in Java, and Java itself is intended to be WORA (Write Once, Run Anywhere), you can develop (and, perhaps more importantly, debug) a servlet on Windows NT. The servlet can then be deployed on to a Unix server with a high degree of confidence that it will function correctly. Also, as no code is ever executed on the client, you know what version of Java is running and can develop for that one and only that one.
Once a servlet has been requested it can stay in memory (at the garbage collector's discretion), which will allow any repeat call to use a small, lightweight, method call so unlike CGI it is not necessary to spawn a new process or invoke an interpreter. Since servlets are multi-threaded, separate threads can handle multiple concurrent requests, which gives high scalability.
Since this is Java you have access to the power of the Java API - multi-threading, networking, database access, internationalisation and much more - all of which is available for you to use without having to write (or debug) a line of code. If something does not come as standard with the JDK (Java Developer Kit), there are lots of third-party libraries available and these are just as usable with servlets as in 'normal' Java programs.
Servlets use classes and interfaces from two packages: javax.servlet and javax.servlet.http. Every servlet must implement the javax.servlet.Servlet interface, however most developers choose to extend javax.servlet.http.HttpServlet as it has easier access to the information supplied by the http protocol.
Unlike a Java application there is no main() method - like a service, your code does not do anything until it is invoked, in this case by the web server. When a web server wants something doing it will call the servlets service() method. The service() method accepts two parameters; one of type HttpServletRequest and one of type HttpServletResponse.
A servlet typically does not override the service() method, instead it overrides one, or more, of the 'do' methods; doGet, doPost, doPut, doDelete. The HttpServlet.service() will call the appropriate 'do' method, forwarding the request and response objects.
The http request object, extended from ServletRequest, encapsulates information about the client request; parameters and attributes along with support for cookies, session tracking and access to the HTTP header information. The http response object, extended from ServletResponse, is used to send data back to the client and manipulate HTTP protocol-specific data including response headers and status codes, cookies and session tracking. Binary information can be streamed or written and characters can be written out. This allows servlets to be written which can manipulate images, access databases, and do anything you wish.
The servlet that follows enumerates all the input data it receives… more useful than you might think…
import javax.servlet.*; import javax.servlet.http.*; import java.util.Enumeration; public class ShowData extends HttpServlet { protected void doGet(HttpServletRequest req , HttpServletResponse resp) throws ServletException, java.io.IOException { resp.setContentType("text/html"); printWriter out = res.getWriter(); out.println("<html><body>"); out.println("A get operation<br>"); out.println(enumParameter(req).toString()); out.println("</body></html>"); } protected void doPost(HttpServletRequest req , HttpServletResponse resp) throws ServletException, Java.io.IOException { resp.setContentType("text/html"); printWriter out = res.getWriter(); out.println("<html><body>"); out.println("A post operation<br>"); out.println(enumParameter(req).toString()); out.println("</body></html>"); } private StringBuffer enumParameters( HttpServletRequest req) throws ServletException, java.io.IOException { StringBuffer buffer = new StringBuffer( "Parameters supplied to the ShowData servlet:<BR><BR>"); Enumeration values = req.getParameterNames(); while(values.hasMoreElements()) { String name=(String)values.nextElement(); String value[] = req.getParameterValues(name); for(int i = 0; i < value.length; ++i){ buffer.append(name).append(" ["). append(i).append("] : "). append(value[i]).append("<br>"); } } return buffer; } }
The example above splits easily into three sections: doGet, doPost and enumParameters. enumParameters is, obviously, the work horse with the others just saying how the parameters were passed to the servlet. Easy isn't it?
Writing servlets is not without its heartaches. The main problem is debugging. If like me, you write perfect code every time, first time, you have nothing to worry about. I wish. So, you write the code, it compiles, you write the surrounding html, fire off navigator and… nothing. What do you do? Here are some hints…
-
Check the logs for problems. The web server writes here, so does the Servlet Engine.
-
Output extra information - a return to 'proper' debugging as the old timers will tell you - "I remember when…"
-
Examine your inputs - the HttpServletRequest object; sometimes we do not get what we want. Ensure what you do get is what you expect.
-
Check the classpath of the servlet: System.getProperty( "Java.class.path"), remember it is probably running as either a demon or service with all the limitations imposed. Programs using JNI can be especially difficult to work out why it does not work.
-
Avoid unnecessary creation of objects - this wastes both time and memory and may block the JVM while it is doing so (JVM dependent).
-
Do not concatenate - append. StringBuffers are always an easy method of optimising string handling in Java and it is much more important with servlets.
-
Limit synchronization. Synchronise whenever necessary, but only when necessary. If this is a problem, create a pool of objects and serve the client from them, or better yet, buy a third party pooling class (saves you debugging yet another implementation).
-
Run JWS (Java Web Server) under a debugger and use this to load your servlet.
JavaServer Pages are Sun's equivalent to Microsoft's ActiveServer Pages. Just like ASP, JSP is a method of embedding Java code within html pages. What has this to do with servlets? Everything. Unlike ASP, JSP is not interpreted. Upon the first request for a page containing JSP the Servlet Engine takes the html, creates a Java file containing all the code, serialises out the text to a file, compiles the Java into a servlet and invokes it. The servlet serialises in the text from the file and proceeds to write out to the response object the html while executing the Java code. The next request from a client will start the process by invoking the servlet. Simplicity.
This gives several advantages and as usual, some disadvantages:
-
if the html file alters the servlet is regenerated.
-
easy for experienced developers to write quick and dirty solutions.
-
difficult for non-technical people to understand let alone maintain or extend.
-
unless very careful the data and display, content and presentation information are intermixed. This is the same as the argument for three tier programs. Splitting off the code to retrieve the data from the business objects and separating the GUI gives interfaces that can be independently tested.
The last disadvantage is, in my opinion, the big problem with both JSP and ASP. If JSP is written correctly, the embedded Java should only manipulate business objects. If this is not the case then the page/content becomes extremely difficult to maintain and, after all, do you want to continue to maintain projects forever? Every time 'web designers' change the colour scheme, are you willing to make sure they do not break something? I did not think so.
XML (eXtended Markup Language) - this is the technology of the moment, along with XSL (eXtended Stylesheet Language) and XSLT (eXtended Stylesheet Language Transformation) the data can be completely separated from the layout. Wow! The data team can be taught to write XML (especially if they are forced to use a validating parser) and the design team can be shown how to alter the XSL(T) file to display the page as they want. Nothing for the developer to do - I like this. Oh dear, here comes the boss. He wants some dynamic content. He wants the sales database linked to the web. Problem - XML is static.
The solution (in case you did not guess) is being developed by the XML Apache group [cocoon]. XSP is for XML what JSP is for html. It allows embedding Java within XML. It works along similar principles to JSP; it takes the XML, creates a Java file, compiles it to a servlet and invokes it. One of the reasons this approach is so much better than JSP is that the servlet only produces data. XSL still controls the styling of the data, so once the XML is written the design team can change how it is displayed without bothering the developer.
Servlets are a very good example of how to write web server extensions and you can see that several more new technologies are being built on and around their functionality. They are simple to write. I recommend that you write a couple before moving onto JSP and XML, as your ability to program in these environments will be greatly enhanced by opening the Java files created and understanding what has been generated from your original files. Both JSP and XSP are evolving extremely quickly. XSP is especially useful by completely separating content from presentation; it really is amazing what it can do. XML also has the advantage that it can be transformed into a multitude of other mark-up forms: WML (WAP (Wireless Application Protocol) Markup Language), SVG (Scalable Vector Graphics) and even PDF (Portable Document Format) (using FOP3).
Wow, my first article and written in under 3 hours! Please do not be too critical but do feel free to contact me. I have to admit however that I could not have written this thing so fast without the Java Servlet bible [Hunter-]. If you are planning to write any servlets this book will be your constant companion.
[jakarta] http://jakarta.apache.org Servlet Engine with support for JSP
[cocoon] http://xml.apache.org Cocoon XML publishing engine
Notes:
More fields may be available via dynamicdata ..