Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Aphorismen
Applications
Business Economics & Admin.
My Computers
Cooking
Devices
Folders
Food
Hardware
Infos
Software Development
Sports
Operation Instructions
Todos
Test
Help
Glossary
Community portal
adaptions
Sidebar anpassen
Wiki RB4
Search
Search
Create account
Log in
Personal tools
Create account
Log in
Pages for logged out editors
learn more
Contributions
Talk
Editing
Servlets
Page
Discussion
English
Read
Edit
View history
Toolbox
Tools
move to sidebar
hide
Actions
Read
Edit
View history
General
What links here
Related changes
Special pages
Page information
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Introduction== ===Disadvantages of other Techniques=== 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=== 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: *'''<code>public void init(ServletConfig config) throws ServletException</code>''' 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. *'''<code>public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException</code>''' 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. *'''<code>public void destroy()</code>''' 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=== {| border=1 cellpadding=2 cellspacing=0 |- |String getContextPath() | returns aus URL <Protocoll>://<server>/<ContextPath>/<Rest> den ContextPath mit leading /. |} ===Response=== Einige Methoden (u.a. doGet()) eines Servlets haben als Parameter eine Variable <code>response</code> vom Typ <code>HttpServletResponse</code>. Die wichtigste Aufgabe ist es die Ausgabe über die Methode <code>getWriter()</code> zu ermöglichen. <code>HttpServletResponse</code> hat folgende Methoden: {| border=1 cellpadding=2 cellspacing=0 |- |PrintWriter getWriter() | |} ====PrintWriter==== Die Ausgabeklasse <code>PrintWriter</code> hat folgenden Methoden: {| border=1 cellpadding=2 cellspacing=0 |- |println(<String>) | |} ===Servlet Scope Objects=== 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==== 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 <code>javax.servlet.GenericServlet.getServletContext()</code> übergeben. ====Session Informationen==== 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== ===Parameter abfragen=== 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=== Dazu dient die selbstentwickelte Klasse RequestHelper und die Methode dumpParameter(); ===Anfragen weiterleiten=== String URL ="/xx/yy/aa.jsp"; getServletContext().getRequestDispatcher(URL).forward(request,response); ===Logging=== //schreibt in file <Tomcat>/logs/localhost_log.<Date>.txt log("blablabla");
Summary:
Please note that all contributions to Wiki RB4 may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see
Uwe Heuer Wiki New:Copyrights
for details).
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Toggle limited content width