600 likes | 1.27k Views
Java Servlets & JSP. Introduction: General Problem.
E N D
Introduction: General Problem HTML, short for Hypertext Markup Language, is the predominant markup language for web pages. It provides a means to describe the structure of text-based information in a document — by denoting certain text as headings, paragraphs, lists, and so on — and to supplement that text with interactive forms, embedded images, and other objects. HTTP POST & GET Methods • The POST method is desiged to allow a uniform function to cover 1. Posting a message to a bulletin board topic, newsgroup, mailing list, or similar group of articles; 2. Adding a file to a directory; • HTTP GET: Information retrieval (considered “safe” )
The Java Servlet API The Java Servlet API allows a software developer to add dynamic content to a Web server using the Java platform. The generated content is commonly HTML, but may be other data such as XML. Servlets are the Java counterpart to non-Java dynamic Web content technologies such as PHP, CGI and ASP.NET. Servlets can maintain state across many server transactions by using HTTP cookies, session variables or URL rewriting. • The original servlet specification was created by Sun Microsystems (version 1.0 was finalized in June 1997). • Starting with version 2.3, the servlet specification was developed under the Java Community Process. • As of May 10, 2006, the current version of the servlet specification is 2.5 (Requires J2SE 5.0, supports annotations).
Life Cycle of a Servlet The Servlet life cycle consists of the following steps: • The Servlet class is loaded by the container during start-up. • The container calls the init() method. This method initializes the servlet and must be called before the servlet can service any requests. In the entire life of a servlet, the init() method is called only once. • After initialization, the servlet can service client-requests. • Each request is serviced in its own separate thread. • The container calls the service() method of the servlet for every request. The service() method determines the kind of request being made and dispatches it to an appropriate method to handle the request. • The developer of the servlet must provide an implementation for these methods. If a request for a method that is not implemented by the servlet is made, the method of the parent class is called, typically resulting in an error being returned to the requester. • Finally, the container calls the destroy() method which takes the servlet out of service. The destroy() method like init() is called only once in the life-cycle of a Servlet.
Servlet Containers • A Servlet container is a specialized web server that supports Servlet execution. It combines the basic functionality of a web server with certain Java/Servlet specific optimizations and extensions – such as an integrated Java runtime environment, and the ability to automatically translate specific URLs into Servlet requests. • Individual Servlets are registered with a Servlet container, providing the container with information about what functionality they provide, and what URL or other resource locator they will use to identify themselves. • The Servlet container is then able to initialize the Servlet as necessary and deliver requests to the Servlet as they arrive. • Many containers have the ability to dynamically add and remove Servlets from the system, allowing new Servlets to quickly be deployed or removed without affecting other Servlets running from the same container. • Servlet containers are also referred to as web containers or web engines.
JSP Introduction • JavaServer Pages (JSP) is a Java technology that allows software developers to dynamically generate HTML, XML or other types of documents in response to a Web client request. The technology allows Java code and certain pre-defined actions to be embedded into static content • The JSP syntax adds additional XML-like tags, called JSP actions, to be used to invoke built-in functionality. Additionally, the technology allows for the creation of JSP tag libraries that act as extensions to the standard HTML or XML tags. Tag libraries provide a platform independent way of extending the capabilities of a Web server. • JSPs are compiled into Java Servlets by a JSP compiler. A JSP compiler may generate a servlet in Java code that is then compiled by the Java compiler, or it may generate byte code for the servlet directly. JSPs can also be interpreted on-the-fly reducing the time taken to reload changes.
JSP syntax A JavaServer Page may be broken down into the followingpieces: • Static data such as HTML • JSP directives such as the include directive • JSP scripting elements and variables • JSP actions • Custom tags with correct library
JSP scripting elements and objects The following JSP implicit objects are exposed by the JSP container and can be referenced by the programmer: • out The JSPWriter used to write the data to the response stream. • page The servlet itself. • pageContext A PageContext instance that contains data associated with the whole page. A given HTML page may be passed among multiple JSPs. • request The HttpServletRequest object that provides HTTP request information. • response The HTTP response object that can be used to send data back to the client. • session The HTTP session object that can be used to track information about a user from one request to another. • config Provides servlet configuration data. • application Data shared by all JSPs and servlets in the application. • exception Exceptions not caught by application code .
Scripting elements There are three basic kinds of scripting elements that allow java code to be inserted directly into the servlet. • A declaration tag places a variable definition inside the body of the java servlet class. Static data members may be defined as well. <%! int serverInstanceVariable = 1; %> Declaration tags also allow methods to be defined. • A scriptlet tag places the contained statements inside the _jspService() method of the java servlet class. <% int localStackBasedVariable = 1; out.println(localStackBasedVariable); %> • An expression tag places an expression to be evaluated inside the java servlet class. Expressions should not be terminated with a semi-colon . <%= "expanded inline data " + 1 %> • Also we can use the following tag to give comments in jsp: <%-- give your comments here --%>
JSP directives JSP directives control how the JSP compiler generates the servlet. The following directives are available: • include • The include directive informs the JSP compiler to include a complete file into the current file. It is as if the contents of the included file were pasted directly into the original file. This functionality is similar to the one provided by the C preprocessor. Included files generally have the extension "jspf" (for JSP Fragment): <%@ include file="somefile.jspf" %> • page • <%@ page import="java.util.*" %> //example import • <%@ page contentType="text/html" %> //example contentType • <%@ page isErrorPage=false %> //example for non error page • <%@ page isThreadSafe=true %> //example for a thread safe JSP • <%@ page session=true %> //example for using session binding • <%@ page buffer=20 %> //example for setting Buffer Size • taglib • The taglib directive indicates that a JSP tag library is to be used. The directive requires that a prefix be specified (much like a namespace in C++). <%@ taglib prefix="myprefix" uri="taglib/mytag.tld" %> JSP Tag Libraries <myprefix:myaction> <%-- the start tag %> ... </myprefix:myaction> <%-- the end tag %>
JSP actions JSP actions are XML tags that invoke built-in web server functionality. They are executed at runtime. Some are standard and some are custom(which are developed by Java developers) Following are the standard ones: • jsp:include Similar to a subroutine, the Java servlet temporarily hands the request and response off to the specified JavaServer Page. Control will then return to the current JSP, once the other JSP has finished. • jsp:param Can be used inside a jsp:include, jsp:forward or jsp:params block. Specifies a parameter that will be added to the request's current parameters. • jsp:forward Used to hand off the request and response to another JSP or servlet. Control will never return to the current JSP. • jsp:plugin Older versions of Netscape Navigator and Internet Explorer used different tags to embed an applet. This action generates the browser specific tag needed to include an applet. • jsp:fallback The content to show if the browser does not support applets. • jsp:getProperty Gets a property from the specified JavaBean. • jsp:setProperty Sets a property in the specified JavaBean. • jsp:useBean Creates or re-uses a JavaBean available to the JSP page.
Examples of tags jsp:include <html> <head></head> <body> <jsp:include page="mycommon.jsp" > <jsp:param name="extraparam" value="myvalue" /> </jsp:include> name:<%=request.getParameter("extraparam")%> </body> </html> jsp:plugin <jsp:plugin type=applet height="100%" width="100%" archive="myjarfile.jar,myotherjar.jar" codebase="/applets" code="com.foo.MyApplet" > <jsp:params> <jsp:param name="enableDebug" value="true" /> </jsp:params> <jsp:fallback> Your browser does not support applets. </jsp:fallback> </jsp:plugin> jsp:useBean <jsp:useBean id="myBean" class="com.foo.MyBean" scope="request" /> <jsp:getProperty name="myBean" property="lastChanged" /> <jsp:setProperty name="myBean" property="lastChanged" value="<%= new Date()%>" />
Example Regardless of whether the JSP compiler generates Java source code for a servlet or emits the byte code directly, it is helpful to understand how the JSP compiler transforms the page into a Java servlet. For an example, consider the following input JSP and its resulting generated Java Servlet. Input JSP <%@ page errorPage="myerror.jsp" %> <%@ page import="com.foo.bar" %> <html> <head> <%! int serverInstanceVariable = 1;%> ... <% int localStackBasedVariable = 1; %> <table> <tr> <td><%= toStringOrBlank( "expanded inline data " + 1 )%> </td> </tr> ...
Resulting servlet package jsp_servlet; import javax.servlet.*; ... import com.foo.bar; //imported as a result of <%@ page import="com.foo.bar" %> import ... class _myservlet implements javax.servlet.Servlet, javax.servlet.jsp.HttpJspPage { //inserted as a //result of <%! int serverInstanceVariable = 1;%> int serverInstanceVariable = 1; ... public void _jspService( javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response ) throws javax.servlet.ServletException, java.io.IOException { javax.servlet.ServletConfig config = ...; //get the servlet config Object page = this; PageContext pageContext = ...; //get the page context for this request javax.servlet.jsp.JspWriter out = pageContext.getOut(); HttpSession session = request.getSession( true ); try { out.print( "<html>\r\n" ); out.print( "<head>\r\n" ); ... //from <% int localStackBasedVariable = 1; %> int localStackBasedVariable = 1; ... out.print( "<table>\r\n" ); out.print( " <tr><td>" ); //from <%= toStringOrBlank( "expanded inline data " + 1 ) %> out.print( toStringOrBlank( "expanded inline data " + 1 ) ); out.print( " </td></tr>\r\n" ); ... } catch ( Exception _exception ) { //clean up and redirect to error page in <%@ page errorPage="myerror.jsp" %> } } }
Non-commercial web containers • Apache Tomcat (formerly Jakarta Tomcat) is an open source web container available free of charge under the Apache Software License. It is used in the official reference implementation and has a reputation for being stable. • Geronimo Application Server is a full J2EE implementation by Apache. • Jetty • Jaminid contains a higher abstraction than servlets. • Enhydra • jo! • Winstone supports specification v2.4, has a focus on minimal configuration and the ability to strip the container down to only what you need. • tjws spec 2.4, small footprint, modular design
Commercial web containers Commercial web containers • Java System Application Server • Java System Web Server • Caucho's Resin Server • BEA WebLogic Server or Weblogic Express • Borland Enterprise Server • Oracle Application Server • IBM's WebSphere • Macromedia JRun • IronFlare Orion Application Server • WebObjects Commercial open source web containers • JBoss • GlassFish • LiteWebServer