Sie sind auf Seite 1von 34

Java Servlets

A servlet is a java class that can be loaded dynamically to expand the functionality of a server. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company's order database. Servlets are to servers what applets are to browsers. Servlets operate solely within the domain of the server: unlike applets, they do not require support for Java in the web browser. A servlet runs inside a Java Virtual Machine (JVM) on the server, so it is safe and portable.

Servlets have become most widely used within HTTP servers.

The Advantages of Servlets


Replacement of CGI
The Common Gateway Interface, normally referred to as CGI, was one of the first practical techniques for creating dynamic content.

With CGI, a web server passes certain requests to an external program written in C/C++/Perl. The output of this program is then sent to the client. When a server receives a request that accesses a CGI program, it must create a new process to run the CGI program and then pass to it, via environment variables and standard input, every bit of information that might be necessary to generate a response. Creating a process for every such request requires time and significant server resources, which limits the number of requests a server can handle concurrently. Since servlets execute within the address space of a web server, creating a separate process to handle each client request is not necessary. Hence, the performance is significantly better.

Portability
Because servlets are written in Java and conform to a well-defined and widely accepted API, they are highly portable across operating systems and across server implementations. We can develop a servlet on a Windows NT machine running the Java Web Server and later deploy it effortlessly on a Unix server running Apache. With servlets, we can truly "write once, serve everywhere."

Power

Servlets can harness the full power of the core Java APIs: networking and URL access, multithreading, image manipulation, data compression, database connectivity,

internationalization, remote method invocation (RMI), and object serialization, among others. Servlets are also well suited for enabling client/server communication.

Efficiency
Servlet invocation is highly efficient. Once a servlet is loaded, it generally remains in the server's memory as a single object instance. Unlike with CGI, there's no process to spawn or interpreter to invoke, so the servlet can begin handling the request almost immediately. Multiple, concurrent requests are handled by separate threads, so servlets are highly scalable.

Safety

Servlets support safe programming practices on a number of levels. Because they are written in Java, servlets inherit the strong type safety of the Java language. Java's automatic garbage collection and lack of pointers mean that servlets are generally safe from memory management problems like dangling pointers, invalid pointer references, and memory leaks. Servlets can handle errors safely, due to Java's exceptionhandling mechanism. A server can further protect itself from servlets through the use of a Java security manager. A server can execute its servlets under the watch of a strict security manager that, for example, enforces a security policy designed to prevent a malicious or poorly written servlet from damaging the server file system.

Extensibility and Flexibility


The Servlet API is designed to be easily extensible. As it stands today, the API includes classes that are optimized for HTTP servlets. But at a later date, it could be extended and optimized for another type of servlets, either by Sun or by a third party. It is also possible that its support for HTTP servlets could be further enhanced. Servlets are also quite flexible. An HTTP servlet can be used to generate a complete web page; it can be added to a static page using a <SERVLET> tag in what's known as a server-side include; and it can be used in cooperation with any number of other servlets to filter content in something called a servlet chain.

The Servlet API


Servlets use classes and interfaces from two packages: javax.servlet and javax.servlet.http . The javax.servlet package contains classes to support generic, protocol-independent servlets. These classes are extended by the classes in the javax.servlet.http package to add HTTP-specific functionality. The top-level package name is javax instead of the familiar java, to indicate that the Servlet API is a standard extension. Every servlet must implement the javax.servlet.Servlet interface.

Most servlets implement it by extending one of two special classes: javax. servlet.GenericServlet or javax.servlet.http.HttpServlet . A protocol-independent servlet should subclass GenericServlet, while an HTTP servlet should subclass HttpServlet, which is itself a subclass of GenericServlet with added HTTP-specific functionality. All servlets implement javax.servlet.Servlet interface, either directly or, more commonly, by extending a class that implements it such as
javax.servlet.http.HttpServlet

Unlike a regular Java program, and just like an applet, a servlet does not have a main() method. Instead, certain methods of a servlet are invoked by the server in the process of handling requests. Each time the server dispatches a request to a servlet, it invokes the servlet's service() method. A generic servlet should override its service() method to handle requests as appropriate for the servlet. The service() method accepts two parameters: a request object and a response object. The request object tells the servlet about the request, while the response object is used to return a response.

The following figure shows how a generic servlet handles requests.

In contrast, an HTTP servlet usually does not override the service() method. Instead, it overrides doGet() to handle GET requests and doPost() to handle POST requests. An HTTP servlet can override either or both of these methods, depending on the type of requests it needs to handle. The following figure shows how an HTTP servlet handles GET and POST requests.

The

the javax.servlet and javax.servlet.http packages are largely support classes.

remainder

in

For

the ServletRequest and ServletResponse classes in javax.servlet provide access to generic server requests and responses, while HttpServletRequest and HttpServletResponse in javax.servlet.http provide access to HTTP requests and responses.

example,

Client Interaction
When a servlet accepts a call from a client, it receives two objects: A ServletRequest, which encapsulates the communication from the client to the server. A ServletResponse, which encapsulates the communication from the servlet back to the client. ServletRequest and ServletResponse are interfaces defined by the javax.servlet package.

The ServletRequest Interface


The ServletRequest interface allows the servlet access to:

Information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names of the remote host that made the request and the server that received it. The input stream, ServletInputStream. Servlets use the input stream to get data from clients that use application protocols such as the HTTP POST method.

The ServletResponse Interface


The ServletResponse interface gives the servlet methods for replying to the client. It: o Allows the servlet to set the content length and MIME type of the reply. o Provides an output stream, ServletOutputStream, and a Writer through which the servlet can send the reply data.

The javax.servlet.http package also contains an HttpSession class that provides built-in session tracking functionality. HTTP servlets also have objects that provide cookies. The servlet writer uses the cookie API to save data with the client and to retrieve this data as needed.

The Servlet Life Cycle


Each servlet has the same life cycle: A server loads and initializes the servlet The servlet handles zero or more client requests The server removes the servlet (some servers do this step only when they shut down)

Initializing a Servlet
When a server loads a servlet, the server runs the servlet's init() method. Initialization completes before client requests are handled and before the servlet is destroyed. The server calls the init method once, when the server loads the servlet, and will not call the init method again unless the server is reloading the servlet. The server can not reload a servlet until after the server has destroyed the servlet by running the destroy method.

Interacting with Clients


After initialization, the servlet is able to handle client requests. An HTTP Servlet handles client requests through its service() method. The service method supports standard HTTP client requests by dispatching each request to a method designed to handle that request.

The methods to which the service method delegates HTTP requests include, o doGet(), for handling GET requests o doPost(), for handling POST requests

Destroying a Servlet
Servlets run until the server destroys them, for example, at the request of a system administrator. When a server destroys a servlet, the server runs the servlet's destroy() method. The method is run once; the server will not run the destroy() method again until after the server reloads and reinitializes the servlet.

Basic Servlet Structure

Here's the outline of a basic servlet that handles GET requests.

A Simple Servlet

//Filename: HelloWorld.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet {

public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("Hello World"); }
}

GET requests are requests made by browsers when the

user types in a URL on the address line, follows a link from a Web page, or makes an HTML form that does not specify a METHOD. Servlets can also very easily handle POST requests, which are generated when someone creates an HTML form that specifies METHOD="POST". To be a servlet, a class should extend HttpServlet and override doGet or doPost (or both), depending on whether the data is being sent by GET or by POST. These methods take two arguments: an HttpServletRequest and an HttpServletResponse. The HttpServletRequest has methods that let you find out about incoming information such as FORM data, HTTP request headers, and the like. The HttpServletResponse has methods that lets you specify the HTTP response headers (Content-Type, Set-Cookie, etc.), and, most importantly, lets you obtain a PrintWriter used to send output back to the client. For simple servlets, most of the effort is spent in println statements that generate the desired page.

Note that doGet and doPost throw two exceptions, so you are required to include them in the declaration. Also note that you have to import classes in java.io (for PrintWriter, etc.), javax.servlet (for HttpServlet, etc.), and javax.servlet.http (for HttpServletRequest and HttpServletResponse). Finally, note that doGet and doPost are called by the service method, and sometimes you may want to override service directly, e.g. for a servlet that handles both GET and POST request.

Compiling and Installing the Servlet Install the JDK. Make sure JDK 1.5 or 1.4 is installed and your PATH and CLASSPATH is set. Configure Tomcat. Download tomcat from http://tomcat.apache.org Set the JAVA_HOME variable. Set it to refer to the base JDK directory, not the bin subdirectory. Change the port to 80. Edit install_dir/conf/server.xml and change the port attribute of the Connector element from 8080 to 80. Turn on servlet reloading. Edit install_dir/conf/context.xml and change <Context> to <Context reloadable="true">. Enable the invoker servlet. Go to install_dir/conf/web.xml and uncomment the <servlet> and <servlet-mapping> elements that map the invoker servlet.

<servlet> <servlet-name>invoker</servlet-name> <servlet-class> org.apache.catalina.servlets.InvokerServlet </servlet-class> ... </servlet> ... <servlet-mapping> <servlet-name>invoker</servlet-name> <url-pattern>/servlet/*</url-pattern> </servlet-mapping> Set the CATALINA_HOME variable. Optionally, set CATALINA_HOME to refer to the top-level Tomcat installation directory. Test the server Start/Stop the Apache Tomcat service from Control Panel-Administrative Tools-Services-Apache Tomcat Make shortcuts to the Tomcat startup & shutdown Scripts. Put shortcuts to

install_dir/bin/startup.bat and install_dir/bin/shutdown.bat on your desktop. Run the file tomcat5w.exe located in C:\Program Files\Apache Software Foundation\Tomcat 5.5\bin to start and stop the server in tomcat5. Verify that you can start the server. Double-click install_dir/bin/startup.bat and try accessing http://localhost/. Put the complete path of servelet-api.jar and jspapi.jar in your classpath. These files are located at C:\Program Files\Apache Software Foundation\Tomcat 5.5\common\lib\servletapi.jar and C:\Program Files\Apache Software Foundation\Tomcat 5.5\common\lib\jsp-api.jar Compile and test some simple servlets Test a packageless servlet. Compile a simple servlet, put the .class file in install_dir/webapps/ROOT/WEB-INF/classes, and access it with http://localhost/servlet/ServletName. Test a servlet that uses packages. Compile the servlet, put the .class file in install_dir/webapps/ROOT/WEBINF/classes/packageName, and access it with http://localhost/servlet/packageName.ServletNam e. Check that you can access your own HTML & JSP pages. Drop some simple HTML and JSP pages

into install_dir/webapps/ROOT and access with http://localhost/filename. Bookmark the servlet & JSP javadocs. install_dir/webapps/tomcatdocs/servletapi/index.html install_dir/webapps/tomcatdocs/jspapi/index.html to bookmarks/favorites list.

them Add and your

Common Requests: GET and POST


The Most common HTTP requests: GET and POST. GET requests: Getting information - Appended to the URL in a query string (can only send limited amount of data, to describe what's desired). .../servlet/ViewCourse?name=servlets_codecamp Can be bookmarked and emailed. POST requests: Sending information. Can send any amount of data, directly over socket connection without changing the URL. - .../servlet/PlaceOrderProcess - Can Not be bookmarked and emailed.

Controlling Concurrent Shared Resources

Access

to

In a multithreaded server, it is possible for shared resources to be accessed concurrently. A web container typically creates a thread to handle each request.

Many Threads, One Servlet Instance

If you want to ensure that a servlet instance handles only one request at a time, a servlet can implement the SingleThreadModel interface.

public interface SingleThreadModel


If a servlet implements this interface, you are guaranteed that no two threads will execute concurrently in the servlet's service method. The servlet container can make this guarantee by synchronizing access to a single instance of the servlet, or by maintaining a pool of servlet instances and dispatching each new request to a free servlet.

This interface has no methods. Note that SingleThreadModel does not solve all thread safety issues. For example, session attributes and static variables can still be accessed by multiple requests on multiple threads at the same time, even when SingleThreadModel servlets are used. It is recommended that a developer take other means to resolve those issues instead of implementing this interface, such as avoiding the usage of an instance variable or synchronizing the block of the code accessing those resources. This interface is deprecated in Servlet API version 2.4.

Debugging Servlets
Here are a few hints and suggestions that may help in debugging servlets

Check the Logs


o Check the logs. o Most servers output an error log where you can find a list of all the errors observed by the server and an event log where you can find a list of servlet events. o The event log may also hold the messages logged by servlets through the log() method.

Output Extra Information


If you don't see an indication of the problem in the server's logs, try having your servlet log extra information with the log()method. o Extracting the extra information from the server's logs can at times be difficult to use. o To make the temporary debugging information easier to find, we can have a servlet output its debug information to the client (through the PrintWriter) or to a console on the server (through System.out).
o

Use a Third-Party Tool


o Third-party tools promise to bring new capabilities and ease of use to the task of servlet debugging. o LiveSoftware, maker of the popular JRun servlet plugin, was the first company to market a tool for servlet debugging. o The product, named ServletDebugger, is designed to help programmatically test and debug a servlet. Return error pages to the client.

Use System.getProperty("java.class.path") from your servlet to help debug classpath problems. Because servlets are often run from web servers with embedded JVMs, it can be hard at times to identify exactly what classpath the JVM is searching. The property "java.class.path" will tell you. Make sure the browser isn't caching a previous request's output by forcing a full reload of the page. With Netscape Navigator, use Shift-Reload; with Internet Explorer use Shift-Refresh. Sometimes stopping and restarting the server also eliminates some problems.

Session Tracking
HTTP is a stateless protocol: it provides no way for a server to recognize that a sequence of requests is all from the same client. So, each client needs to provide a unique identifier that lets the server identify it, or it needs to give some information that the server can use to properly handle the request. A session is used to store information particular to a client. For example a session can be used to: o hold the contents of a customer's shopping cart; o store the number of times a surfer accesses a particular web resource; o hold membership details for a registered user at the site and so on; A session can be created via the getSession() method of the HttpServletRequest. An HttpSession object is returned.

This object can store a set of bindings that associate names with objects. The putValue(), getValue(), getValueNames() and removeValue() methods of HttpSession manage these bindings. It is important to note that the session state is shared among all the servlets that are associated with a particular client. Approaches to Session Tracking Hidden Form Fields URL Rewriting Cookies

Hidden Form Fields

o One way to support anonymous session tracking is to use hidden form fields. o As the name implies, these are fields added to an HTML form that are not displayed in the client's browser. o They are sent back to the server when the form that contains them is submitted. o We include hidden form fields with HTML like this:
<FORM ACTION="/servlet/MovieFinder" METHOD="POST"> ... <INPUT TYPE=hidden NAME="zip" VALUE="94040"> <INPUT TYPE=hidden NAME="level" VALUE="expert"> ... </FORM>

o For hidden fields to work the client must send a hidden form field to the server and the server must always return that same hidden form field. o This tightly coupled dependency between client requests and server responses requires sessions involving hidden form fields to be an unbreakable chain of dynamically generated web pages. o Hidden fields are supported in all the popular browsers; they demand no special server requirements.

URL Rewriting
o URL rewriting is another way to support anonymous session tracking. o With URL rewriting, every local URL the user might click on is dynamically modified, or rewritten, to include extra information. o Due to the limited space available in rewriting a URL, the extra information is usually limited to a unique session ID. o For example, the following URLs have been rewritten to pass the session ID 123:
http://server:port/servlet/Rewritten original http://server:port/servlet/Rewritten? sessionid=123 added parameter

o URL re-writing suffers from the same major disadvantage that hidden form fields do, in that they must be dynamically generated and the chain of HTML page generation should not be broken.

Cookies:

A cookie is a small piece of textual information sent by a web server to a browser that can later be read back from that browser. o When a browser receives a cookie, it saves the cookie and thereafter sends the cookie back to the server each time it accesses a page on that server. o Because a cookie's value can uniquely identify a client, cookies are often used for session tracking. o Cookies were first introduced in Netscape Navigator and quickly became a de facto standard supported in all the popular browsers. o The main purpose of cookies is to identify users and possibly prepare customized Web pages for them.
o

Working with Cookies


provides the javax.servlet.http.Cookie class for working with cookies. The HTTP header details for the cookies are handled by the Servlet API. You create a cookie with the Cookie() constructor:

The

Servlet

API

public Cookie(String name, String value)

This creates a new cookie with an initial name and value. A servlet can send a cookie to the client by passing a Cookie object to the addCookie() method of HttpServletResponse:
public void HttpServletResponse.addCookie(Cookie cookie)

This method adds the specified cookie to the response.

Additional cookies can be added with subsequent calls to addCookie() . Because cookies are sent using HTTP headers, they should be added to the response before you send any content. Browsers are only required to accept 20 cookies per site, 300 total per user, and they can limit each cookie's size to 4096 bytes. The code to set a cookie looks like this:

Cookie cookie = new Cookie("ID", "123"); res.addCookie(cookie);

A servlet retrieves cookies by calling the getCookies() method of HttpServlet- Request:


public HttpServletRequest.getCookies() Cookie[]

This method returns an array of Cookie objects that contains all the cookies sent by the browser as part of the request or null if no cookies were sent. The code to fetch cookies looks like this:

Cookie[] cookies = req.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { String name = cookies[i].getName(); String value = cookies[i].getValue(); } }

We can set a number of attributes for a cookie in addition to its name and value using the various setType( ) methods available. Persistent cookies offer an efficient and easy way to implement session tracking. The biggest problem with cookies is that browsers don't always accept cookies. Sometimes this is because the browser doesn't support cookies. More often, it's because the user has specifically configured the browser to refuse cookies (out of privacy concerns, perhaps). In absence of cookies we may have to resort to Hidden form fields or URL Rewriting.

Session Example
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*;

public class DateServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Get the HttpSession object HttpSession hs = request.getSession(true); /* The getSession() method gets the current session. A new session is created if one does not already exist. The getValue() method is called to obtain the object that is bound to the name date. That object is a Date object that encapsulates the date and time when this page was last accessed..(Ofcourse, there is no such binding when the page is first accessed) A Date object is encapsulating the current date and time is then created. The putValue() method is called to bind the name date to this object. */ // Get writer response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.print("<B>");

// Display date/time of last access

Date date = (Date)hs.getValue("date"); if(date != null) { pw.print("Last access: " + date + "<br>"); } // Display current date/time date = new Date(); hs.putValue("date", date); pw.println("Current date: " + date); } }

HTTP Redirects
sendRedirect
public void sendRedirect(java.lang.String location) throws java.io.IOException Sends a temporary redirect response to the client using the specified redirect location URL. This method can accept relative URLs; the servlet container must convert the relative URL to an absolute URL before sending the response to the client.

encodeURL

public java.lang.String encodeURL(java.lang.String url) Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged. If the browser supports cookies, URL encoding is unnecessary. For robust session tracking, all URLs emitted by a servlet should be run through this method. Otherwise, URL rewriting cannot be used with browsers which do not support cookies.

encodeRedirectURL
public java.lang.String encodeRedirectURL(java.lang.String url) Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged. All URLs sent to the HttpServletResponse.sendRedirect method should be run through this method. Otherwise, URL rewriting cannot be used with browsers which do not support cookies. import javax.servlet.*; import javax.servlet.http.*; public class UrlRedirect extends HttpServlet { public void doGet(HttpServletRequest HttpServletResponse response) request,

throws ServletException, java.io.IOException { String contextPath= "http://localhost:8080"; response.sendRedirect(response.encodeRedirectU rl(contextPath)); } }

Java Server Pages


JavaServer Pages (JSPs) are similar to HTML files, but provide the ability to display dynamic content within Web pages. JSP technology was developed by Sun Microsystems to separate the development of dynamic Web page content from static HTML page design. The result of this separation means that the page design can change without the need to alter the underlying dynamic content of the page. This is useful in the development life-cycle because the Web page designers do not have to know how to create the dynamic content, but simply have to know where to place the dynamic content within the page. To facilitate embedding of dynamic content, JSPs use a number of tags that enable the page designer to insert the properties of a JavaBean object and script elements into a JSP file.

Here are some of the advantages of using JSP technology over other methods of dynamic content creation: .Separation of dynamic and static content o This allows for the separation of application logic and Web page design, reducing the complexity of Web site development and making the site easier to maintain. Platform independence o Because JSP technology is Java-based, it is platform independent. o JSPs can run on nearly any Web application server. o JSPs can be developed on any platform and viewed by any browser because the output of a compiled JSP page is HTML. Component reuse o Using JavaBeans and Enterprise JavaBeans, JSPs leverage the inherent reusability offered by these technologies. o This enables developers to share components with other developers or their client community, which can speed up Web site development. Scripting and tags o JSPs support both embedded JavaScript and tags. o JavaScript is typically used to add page-level functionality to the JSP. o Tags provide an easy way to embed and modify JavaBean properties and to specify other directives and actions.

How JavaServer Pages work

JavaServer Pages are made operable by having their contents (HTML tags, JSP tags and scripts) translated into a servlet by the application server. This process is responsible for translating both the dynamic and static elements declared within the JSP file into Java servlet code that delivers the translated contents through the Web server output stream to the browser. Because JSPs are server-side technology, the processing of both the static and dynamic elements of the page occurs in the server. The architecture of a JSP/servlet-enabled Web site is often referred to as thin-client because most of the business logic is executed on the server. The following process outlines the tasks performed on a JSP file on the first invocation of the file or when the underlying JSP file is changed by the developer. o The Web browser makes a request to the JSP page. o The JSP engine parses the contents of the JSP file. o The JSP engine creates temporary servlet source code based on the contents of the JSP. The generated servlet is responsible for rendering the static elements of the JSP specified at design time in addition to creating the dynamic elements of the page. o The servlet source code is compiled by the Java compiler into a servlet class file. o The servlet is instantiated. The init and service methods of the servlet are called, and the servlet logic is executed. o The combination of static HTML and graphics combined with the dynamic elements specified in the original JSP page definition are sent to the Web

browser through the output stream of the servlets response object.

Subsequent invocations of the JSP file will simply invoke the service method of the servlet created by the above process to serve the content to the Web browser. The servlet produced as a result of the above process remains in service until the application server is stopped, the servlet is manually unloaded, or a change is made to the underlying file, causing recompilation.

Syntax Summary
JSP Element JSP Expression Syntax Interpretation Expression is evaluated and placed in output. Code is inserted in service method. Code is inserted

<%= expression %>

JSP Scriptlet JSP Declaration

<% code %> <%! code %>

in body of servlet class, outside of


service

JSP page Directive

<%@ page att="val" %>

JSP include Directive

<%@ include file="url" %>

JSP Comment

<%-- comment --%>

<jsp:include page="relative The jsp:include URL" Action flush="true"/>


<jsp:useBean att=val*/>

method. Directions to the servlet engine about general setup. A file on the local system to be included when the JSP page is translated into a servlet. Comment; ignored when JSP page is translated into servlet. Includes a file at the time the page is requested.

The jsp:useBean or Find or build a <jsp:useBean att=val*> Java Bean. Action ...
</jsp:useBean>

<jsp:setProperty jsp:setProperty att=val*/>


The

Set bean properties,

Action

either explicitly or by designating that value comes from a request parameter. Retrieve and output bean properties. Forwards request to another page.

<jsp:getProperty The name="propertyN jsp:getProperty ame" Action value="val"/> <jsp:forward The jsp:forward page="relative Action URL"/>
JSP Example:

Put the test folder containing the .html and .jsp files in the tomcat_install/webapps/ROOT/jsp directory URL to run the example is: http://localhost:8080/jsp/SimpleJSP.jsp

Das könnte Ihnen auch gefallen