Servlets
Introduction[edit]
Disadvantages of other Techniques[edit]
CGI is not without drawbacks. Performance and scalability are big problems since a new process is created for each request, quickly draining a busy server of resources. Sharing resources such as database connections between scripts or multiple calls to the same script is far from trivial, leading to repeated execution of expensive operations. Security is another big concern. Most Perl scripts use the command shell to execute OS commands with user-supplied data, for instance to send mail, search for information in a file, or just leverage OS commands in general. This use of a shell opens up many opportunities for a creative hacker to make the script remove all files on the server, mail the server's password file to a secret account, or do other bad things that the script writer didn't anticipate. The Web server vendors defined APIs to solve some of these problems, notably Microsoft's ISAPI and Netscape's NSAPI. But an application written to these proprietary APIs is married to one particular server vendor. If you need to move the application to a server from another vendor, you have to start from scratch. Another problem with this approach is reliability. The APIs typically support C/C++ code executing in the Web server process. If the application crashes, e.g. due to a bad pointer or division by zero, it brings the Web server down with it. Servlets sind wie der Name schon andeutet server-basierte Java-Klassen, deren grundsätzliche funktionsweise mit der von CGI-Programmen vergleichbar ist. Sie laufen auf dem Server und erstellen dort in der Regel dynamische HTML-Seiten, deren Inhalt zum Beispiel aus Datenbankabfragen resultieren kann.
Concepts[edit]
The Servlet API was developed to leverage the advantages of the Java platform to solve the issues of CGI and proprietary APIs. It's a simple API supported by virtually all Web servers and even load-balancing, fault-tolerant Application Servers. It solves the performance problem by executing all requests as threads in one process, or in a load-balanced system, in one process per server in the cluster. Servlets can easily share resources wie z.B. Datenbankverbindungen as you will see in this article und können diese auch über ein Request hin offenhalten. Zudem ist das Sicherheitskonzept von Java sehr mächtig und die Sprache an sich im Vergleich zu C++ sehr sicher.
A servlet is a Java class and therefore needs to be executed in a Java VM by a service which is called a servlet engine. The servlet engine loads the servlet class the first time the servlet is requested, or optionally already when the servlet engine is started. The servlet then stays loaded to handle multiple requests until it is explicitly unloaded or the servlet engine is shut down. All Servlet API classes and a simple servlet-enabled Web server are combined into the Java Servlet Development Kit (JSDK), available for download at Sun's official Servlet site Beim ersten Zugriff auf ein Servlet beziehungsweise beim Starten des Web-Servers legt die Servlet-Umgebung eine Instanz der gewünschten Java-Klasse an. Die Bearbeitung dieses Request läuft im Prozessraum des Web-Servers als eigenständiger Thread, verwendet aber immer die gleiche Instanz der Servlet-Klasse. Der Entwickler muss dafür Sorge tragen, dass die kritischen Bereiche gegen parallelen Zugriff aus mehreren threads geschützt sind. Man kann durch Implementierung von SingleThreadModell gewährleisten, daß immer nur ein Request durch die service-Methode bearbeitet wird.
A servlet is a Java class that implements the Servlet interface javax.servlet.Servlet. This interface has three methods that define the servlet's life cycle:
public void init(ServletConfig config) throws ServletException
This method is called once when the servlet is loaded into the servlet engine, before the servlet is asked to process its first request. Hier kann zum Beispiel eine Datenbankverbindung initialiisiert werden.
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
This method is called to process a request. It can be called zero, one or many times until the servlet is unloaded. Multiple threads (one per request) can execute this method in parallel so it must be thread safe.
public void destroy()
This method is called once just before the servlet is unloaded and taken out of service.
In der Regel werden Servlets von HttpServlet abgeleitet und überschreiben die doGet()- oder doPost-Methode, können aber auch von GeneralServlet abgeleitet werden.
Request[edit]
| String getContextPath() | returns aus URL <Protocoll>://<server>/<ContextPath>/<Rest> den ContextPath mit leading /. |
Response[edit]
Einige Methoden (u.a. doGet()) eines Servlets haben als Parameter eine Variable response vom Typ HttpServletResponse. Die wichtigste Aufgabe ist es die Ausgabe über die Methode getWriter() zu ermöglichen. HttpServletResponse hat folgende Methoden:
| PrintWriter getWriter() |
PrintWriter[edit]
Die Ausgabeklasse PrintWriter hat folgenden Methoden:
| println(<String>) |
Servlet Scope Objects[edit]
There are four scope objects in servlets which enables sharing information between web components. The scope objects and their corresponding Java classes are listed below:
- Web Context (application) – javax.servlet.ServletContext
- Session – javax.servlet.http.HttpSession
- Request – javax.servlet.HttpServletRequest
- Page – javax.servlet.jsp.PageContext
Servlet Context[edit]
In der Klasse ServletContext können Informationen abgelegt und abgefragt werden, die für alle Servlets der Web-Applikation zur Verfügung stehen. Der Context wird einem Servlet über die Basisklassen-Methode javax.servlet.GenericServlet.getServletContext() übergeben.
Session Informationen[edit]
Servlet container bieten einer Web-Anwendung ein komplettes Session-Managment, daß auf Cookies oder URL-Rewriting basiert (if cookies are disabled than the jsession parameter is added to the url). Das Session-Handling ist im Servlet-API integriert. A session terminates if the web application invokes the invalidate() method on the HttpSession object. Der Zugriff auf das Session Objekt erfolgt über die getSession()-Methode aus HttpServletRequest. Mit dem Parameter true wird ein neues Session Objekt angelegt, wenn noch keins existierte. Diese Kombination entspricht der parameterlosen getSession()-Methode.
HttpSession session = request.getSession(true); // oder HttpSession session = request.getSession();
Um ein Objekt aus einer Session auszulesen oder abzulegen gibt es folgende beiden Methoden:
<Class> x = (<Class>)session.getAttribute(“<Name>”); // returns null or object session.setAttribute(“<Name”>,x);
HowTos[edit]
Parameter abfragen[edit]
Wenn ein Parameter einen Value hat, wird folgende Methode verwendet:
String s = request.getParameter(<Parametername>);
Der Returnwert ist null, wenn der Parameter nicht existiert.
Wenn ein Parameter mehrere Values hat, wird folgende Methode verwendet:
String s[] = request.getParameterValues(<Parametername>);
Parameter ausgeben[edit]
Dazu dient die selbstentwickelte Klasse RequestHelper und die Methode dumpParameter();
Anfragen weiterleiten[edit]
String URL ="/xx/yy/aa.jsp"; getServletContext().getRequestDispatcher(URL).forward(request,response);
Logging[edit]
//schreibt in file <Tomcat>/logs/localhost_log.<Date>.txt
log("blablabla");