Sie sind auf Seite 1von 18

javax.servlet.

Servlet interface

javax.servlet.GenericServlet class implements the Servlet interface. It is an abstract class that provides implementation for all the methods except the service() method of the Servlet interface. The javax.servlet.http.HttpServlet class is an abstract class that extends GenericServlet It adds a new service() method with this signature: protected void service (HttpServletRequest, HttpServletResponse) throws ServletException, java.io.IOException;

All the lines end with CRLFthat is, ASCII values 13 (Carriage Return) and 10 (Line Feed).

The structure of an HTTP request An HTTP message sent by a client to a server is called an HTTP request. The initial line for an HTTP request has three parts, separated by spaces: A method name The local path of the requested resource (URI) The version of HTTP being used A typical request line is
GET /reports/sales/index.html HTTP/1.1

GET, HEAD, or POST. HTTP 1.1 adds five more: PUT, OPTIONS, DELETE, TRACE, and CONNECT.

HEAD An HTTP HEAD request is used to retrieve the meta-information about a resource. HEAD is commonly used to check the time when the resource was last modified on the server before sending it to the client. A HEAD request can save a lot of bandwidth,especially if the resource is very big, since the actual resource would not haveto be sent if the client already had the latest version.

PUT A PUT request is used to add a resource to the server. For example, when we PUT a local file named sample.html to the server myhome.com using the URI http://www.myhome.com/files/example.html, the file becomes a resource on that server and is associated with the URI http://www.myhome.com/files/ example.html. structure of an HTTP response the HTTP version, a response status code that tells the result of the request, and an English phrase describing the status code
HTTP/1.1 200 OK Date: Tue, 01 Sep 2004 23:59:59 GMT Content-Type: text/html Content-Length: 52 <html> <body> <h1>Hello, John!</h1> </body> </html>

sequence of events in HttpServlet 1.The servlet container calls the service(ServletRequest, Servlet-Response) method of HttpServlet. The service(ServletRequest, ServletResponse) method of Http-Servlet calls the service(HttpServletRequest, HttpServlet-Response) method of the same class. Observe that the service method is overloaded in the HttpServlet class.
2. 3 .The

service(HttpServletRequest, HttpServletResponse) method of HttpServlet analyzes the request and finds out which HTTP method is being used. Depending on the HTTP method, it calls the corresponding doXXX() method of the servlet. For example, if the request uses the POST method, it calls the doPost() method of the servlet. NOTE If you override the service methods in your servlet class, you will lose the functionality provided by the HttpServlet class, and the doXXX() methods will not be called automatically. In your implementation, you will have to determine the HTTP method used in the request, and then you will have to call the appropriate doXXX() method yourself. For this reason, its

Understanding ServletResponse ServletResponse declares several generic methods, including getWriter(), getOutputStream(), setContentType(), and so forth. We will now discuss two important methods. PrintWriter getWriter() - returns an object of class java.io.PrintWriter that can be used to send character data to the client. ServletOutputStream : If we want to send a binary file, for example a JAR file, to the client, we will need an OutputStream instead of a PrintWriter. ServletResponse provides the getOutputStream() method that returns an object of class javax.servlet. ServletOutputStream.

If you have already called the get- Writer() method on a ServletResponse object, you cannot call the getOutputStream() method on the same ServletResponse object. If you do, the getOutputStream() method will throw an Illegal- StateException.

Which method does the servlet container call on a servlet to initialize the servlet? A: The init(javax.servlet.ServletConfig) method of the javax.servlet.Servlet interface. The javax.servlet. GenericServlet class implements this method.

Here are the limitations of the getResource() and getResourceAsStream() methods: You cannot pass a URL of any active resourcefor example, a JSP page or servlet to this method. If used improperly, this method can become a security hole; it can read all of the files that belong to this web application, including the files under the WEB-INF directory of this web application.

Request URI = context path + servlet path + path info. Context paths and servlet paths start with a / but do not end with it. HttpServletRequest provides three methodsgetContextPath(), getServletPath() and getPathInfo()to retrieve the context path, the servlet path, and the path info, respectively, associated with a request.

ServletContext: ServletContext attributes set on one JVM are not visible on another JVM.We must use a database or the session to share the information. A servlet container is not required to propagate ServletContextEvents and ServletContextAttributeEvents to different JVMs. This means that changes to the ServletContext in one JVM may not trigger a method call on a ServletContextListener or a ServletContextAttribute- Listener in another JVM. ServletContext initialization parameters are available in all of the JVMs. Recall that ServletContext initialization parameters are specified in the deployment descriptor. HttpSession:

An HttpSession can reside on only one JVM at a time. A servlet container is not required to propagate HttpSessionEvents to different JVMs. Attributes of a session that implement the java.io.Serializable interface are migrated appropriately when the session migrates. This does not mean that if the attributes implement the readObject() and writeObject() methods, they will definitely be called. A container notifies all of the session attributes that implement the HttpSessionActivationListener interface when it migrates the session. A container may throw an IllegalArgumentException in the setAttribute()

method of HttpSession if the attribute is not Serializable.

HttpSessionAttributeListener and HttpSessionBindingEvent HttpSessionBindingListener and HttpSessionBindingEvent HttpSessionListener and HttpSessionEvent HttpSessionActivationListener and HttpSessionEvent. All four listener interfaces extend java.util.EventListener. HttpSessionEvent extends java.util.EventObject and HttpSessionBindingEvent extends HttpSessionEvent.

HttpSessionAttributeListener You may wonder what the difference is between HttpSessionAttributeListener and HttpSessionBindingListener, since both are used for listening to changes in the attribute list of a session. The difference is that HttpSessionAttributeListener is configured in the deployment descriptor and the container creates only one instance of the specified class. HttpSessionBindingEvents generated from all the sessions are sent to this object. On the other hand, HttpSessionBindingListener is not configured in the deployment descriptor. The servlet container calls methods on an object implementing this interface only if that object is added to or removed from a session. While the HttpSessionAttribute- Listener interface is used to track the activity of all the sessions on an application level, the HttpSessionBindingListener interface is used to take actions when certain kinds of objects are added to or removed from a session.

Web resource collectionIdentifies the resources of the application (that is, HTML files, servlets, and so forth) that must be protected from public access. A

user must have appropriate authorization to access resources identified under a web resource collection. Authorization constraintIdentifies the roles that a user can be assigned. Instead of specifying permissions for individual users, permissions are assigned to roles. As discussed earlier, this reduces a tight coupling of permissions and the actual users. For example, an AdminServlet may be accessible to any user who is in the administrator role. At deployment time, any of the actual users may be configured as the administrator. User data constraintSpecifies the way the data must be transmitted between the sender and the receiver. In other words, this constraint specifies the transport layer requirement of the application. It formulates the policies for maintaining data integrity and confidentiality. For example, an application may require the use of HTTPS as a means of communication instead of plain HTTP.

JSP:
jsp:plugin, instructs the JSP engine to generate appropriate HTML code for embedding client-side components, such as applets. This action is not specified in the exam objectives

Translation:

The attribute-value pairs in the directives and standard actions are valid. The same JavaBean name is not used more than once in a translation unit. If we are using a custom tag library, the library is valid. The usage of custom tags is valid.

Compilation

<%! int count = 0 %> http://localhost:8080/chapter10/counter.jsp?jsp_precompile=true

The engine will translate the JSP page and compile the generated servlet class without actually executing the servlet. This can be quite useful during the development phase if we have complex JSP pages that create database connections or access other
J2EE
2

This varies from container to container. Please consult the servlet container documentation for more Information services. Also, it is always a good idea to precompile all the pages. In

this way, we check for syntax errors and keep the pages ready to be served, thus reducing the response time for the first request to each page. The HttpJspPage interface extends the JspPage interface of the same package, which in turn extends the Servlet interface of the javax.servlet package.

jspInit()
The container calls jspInit() to initialize the servlet instance. It is called before any other method, and is called only once for a servlet instance. We normally define this method to do initial or one-time setup, such as acquiring resources and initializing the instance variables that have been declared in the JSP page using <%! ... %> declarations.

<%@ page errorPage="errorHandler.jsp" %> throw new RuntimeException("Name not specified"); <%@ page isErrorPage="true" %> <%=exception.getMessage()%>

pageContext The pageContext variable is of type javax.servlet.jsp.PageContext. The PageContext class is an abstract class, and the JSP engine vendor provides its concrete subclass. Stores references to the implicit objects. If you look at the generated servlet code for the implicit.jsp file (listing 11.2), you will see that the session, application, config, and out implicit variables are initialized using the objects retrieved from pageContext. The pageContext object acts as a one-stop place for managing all the other objects, both userdefined and implicit, used by the JSP page, and it provides the getter methods to retrieve them. Provides convenience methods to get and set attributes in different scopes. These are explained in section 11.3.4. Provides convenience methods, described in table 11.2, for transferring requests to other resources in the web application.

Construct 1
<%

RequestDispatcher rd =request.getRequestDispatcher("other.jsp"); rd.include(request, response); %> Construct 2 <% pageContext.include("other.jsp"); %> Construct 3 <jsp:include page="other.jsp" flush="true"/> <jsp:include page="somePage.jsp"> <jsp:param name="name1" value="value1" /> <jsp:param name="name2" value="value2" /> </jsp:include>

<% pageContext.include("other.jsp"); %> <jsp:include page="other.jsp" /> A: They are functionally similar but with a minor difference. The pageContext.include() method always flushes the output of the current page before including the other components, while <jsp:include> flushes the output of the current page only if the value of flush is explicitly set to true, as in this example:

<jsp:include page="other.jsp" flush="true" /> <function> <name>length</name> <function-class>myFunc.StrMethods</function-class>

<function-signature> java.lang.int length(java.lang.String) </function-signature> </function> </taglib>


<taglib> <taglib-uri> http://myFunc/Functions </taglib-uri> <taglib-location> /WEB-INF/myFunc/Functions.tld </taglib-location> </taglib

The class attribute The class attribute specifies the Java class of the bean instance. If the <jsp:useBean> action cannot find an existing bean in the specified scope, it creates a new instance of the beans class as specified by the value of the class attribute using the classs publicly defined no-argument constructor. Therefore, the class specified by the class attribute must be a public non-abstract class and must have a public noargument constructor. If the class is part of a package, then the fully qualified class name must be specified as mypackage.MyClass. The type attribute The type attribute specifies the type of the variable declared by the id attribute.

Since the declared variable refers to the actual bean instance at request time, its type must be the same as the beans class, or a superclass of the beans class, or an interface implemented by the beans class. Again, if the class or the interface is part of a package, then the fully qualified name must be specified as mypackage.MyClass.

Java virtual machine: Main purpose : To run the compiled Java code across different network with out any modification. Jvm doesnt know abt Java language, it accepts only particular format (.class).A class file contains Java virtual machine instructions (bytecode) and a symbol table as well as ancillary information. How JVM Works: - Class will be loaded using classLoader(it will find the binary representation of classes).. - Loading involves :

Find the binary format of the class.Typically .class format ClassLoader will load the class. If any error occurs during this process then the following subclasses of LinkageError will be thrown.

- ClassFormatError If compiled class is malformed. - UnsupportedClassVersionError Unsupported format. - ClassCircularityError It would be its own superclass. -NoClassDefFoundError No definition for a requested class. - Once it is loaded ,it shld be initialized before invoking the main method . So it must always be linked before it is initialized. - Linking involves verification, preparation and resolution.

Verification -> Checks loaded class is well formed and with proper symbol table and checks whether the code obeys the semantic requirements of JVM.Ensures that binary representation of a class is structurally correct and checks it has valid operation code. Preparation ->Allocation of static storage and any data structure that are used internally by the virtual machine(such as method tables).Assign default values to static field.

IllegalAccessError If we try to access any private method/field. Instantiator If we try to instantiate an abstract class.NoSuchFieldError When we try to invoke a field which is not present in the class.

Resolution -Checks symbolic reference of other class &interfaces, by loading the other classes and checking there references are correct.

-Initialization ->Consist of execution of any class & static variable initializers of the class, in textual order. Before its getting initialized, its super class shld be initialized. In this case Object class will be initialized. Initialization may thus cause loading, linking and initialization errors..

Das könnte Ihnen auch gefallen