Preparation of the material was supported by the project Increasing Internationality in Study Programs of the Department of Computer Science II, project number VP1 2.2 ŠMM-07-K-02-070, funded by The European Social Fund Agency and the Government of Lithuania. Java Technologies Lecture X Valdas Rapševičius Vilnius University Faculty of Mathematics and Informatics 2012.12.31 1
Session Outline You will learn the structure of Java Web Applications and Web Modules You will get in-depth understanding of the main Java web building blocks: Servlet API and JSP 2
Java Web Applications Web components provide the dynamic extension capabilities for a web server. Web components are either Java servlets, JSP pages, or web service endpoints. The client sends an HTTP request to the web server. A web server that implements Java Servlet and JavaServer Pages technology converts the request into an HTTPServletRequest object. This object is delivered to a web component, which can interact with JavaBeans components or a database to generate dynamic content. The web component can then generate an HTTPServletResponse or it can pass the request to another web component. Eventually a web component generates a HTTPServletResponse object. The web server converts this object to an HTTP response and returns it to the client. 3
Java Web Application Technologies Servlets are Java programming language classes that dynamically process requests and construct responses. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content. Although servlets and JSP pages can be used interchangeably, each has its own strengths. Servlets are best suited for service-oriented applications (web service endpoints are implemented as servlets) and the control functions of a presentation-oriented application, such as dispatching requests and handling nontextual data. JSP pages are more appropriate for generating text-based markup such as HTML, Scalable Vector Graphics (SVG), Wireless Markup Language (WML), and XML. Notice that Java Servlet technology is the foundation of all the web application technologies Each technology adds a level of abstraction that makes web application prototyping and development faster and the web applications themselves more maintainable, scalable, and robust. Web components are supported by the services of a runtime platform called a web container. A web container provides services such as request dispatching, security, concurrency, and lifecycle management. It also gives web components access to APIs such as naming, transactions, and email. 4
Web Module Web components and static web content files such as images are called web resources. A web module is the smallest deployable and usable unit of web resources. A web module has a specific structure. The top-level directory of a web module is the document root of the application. The document root is where JSP pages, client-side classes and archives, and static web resources, such as images, are stored. The document root contains a subdirectory named WEB-INF, which contains the following files and directories: web.xml: The web application deployment descriptor. It is required only if you have dynamic content Tag library descriptor files (see Tag Library Descriptors) classes: A directory that contains server-side classes: servlets, utility classes, and JavaBeans components tags: A directory that contains tag files, which are implementations of tag libraries (see Tag File Location) lib: A directory that contains JAR archives of libraries called by server-side classes META-INF subdirectory to contain context.xml runtime deployment descriptor. Note that J2EE Application Server web application runtime DD is named sun-web.xml and is located in the WEB-INF directory along with the web application DD. Application-specific subdirectories (that is, package directories) in either the document root or the WEB- INF/classes/ directory can be created on demand. A web module can be deployed as an unpacked file structure or can be packaged in a JAR file known as a web archive (WAR) file; it uses a.war extension. The web module just described is portable; you can deploy it into any web container that conforms to the Java Servlet Specification. 5
Servlet API Servlet API version Released Platform Important Changes Servlet 3.0 December 2009 JavaEE 6, JavaSE 6 Pluggability, Ease of development, Async Servlet, Security, File Uploading Servlet 2.5 September 2005 JavaEE 5, JavaSE 5 Requires JavaSE 5, supports annotation Servlet 2.4 November 2003 J2EE 1.4, J2SE 1.3 web.xml uses XML Schema Servlet 2.3 August 2001 J2EE 1.3, J2SE 1.2 Addition of Filter Servlet 2.2 August 1999 J2EE 1.2, J2SE 1.2 Becomes part of J2EE, introduced independent web applications in.war files Servlet 2.1 November 1998 Unspecified First official specification, added RequestDispatcher, ServletContext Servlet 2.0 JDK 1.1 Part of Java Servlet Development Kit 2.0 Servlet 1.0 June 1997 6
Servlet A servlet is a Java programming language class. The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. All servlets must implement the Servlet interface, which defines life-cycle methods. When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doget and dopost, for handling HTTP-specific services. The life cycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps. If an instance of the servlet does not exist, the web container Loads the servlet class. Creates an instance of the servlet class. Initializes the servlet instance by calling the init method. Initialization is covered in Initializing a Servlet. Invokes the service method, passing request and response objects. If the container needs to remove the servlet, it finalizes the servlet by calling the servlet s destroy method. Finalization is discussed in Finalizing a Servlet. You can monitor and react to events in a servlet s life cycle by defining listener objects whose methods get invoked when life-cycle events occur. To use these listener objects you must define and specify the listener class. 7
Servlet Life-Cycle Events Object Event Listener Interface and Event Class Web context Initialization and destruction javax.servlet.servletcontextlistener and ServletContextEvent Session Request Attribute added, removed, or replaced Creation, invalidation, activation, passivation, and timeout Attribute added, removed, or replaced A servlet request has started being processed by web components Attribute added, removed, or replaced javax.servlet.servletcontextattributelistener and ServletContextAttributeEvent javax.servlet.http.httpsessionlistener, javax.servlet.http.httpsessionactivationlistener, and HttpSessionEvent javax.servlet.http.httpsessionattributelistener and HttpSessionBindingEvent javax.servlet.servletrequestlistener and ServletRequestEvent javax.servlet.servletrequestattributelistener and ServletRequestAttributeEvent 8
Information Sharing Scope Object Class Accessible From Web context javax.servlet.servletcontext Web components within a web context. Session javax.servlet.http.httpsession Web components handling a request that belongs to the session. Request Subtype of javax.servlet.servletrequest Web components handling the request. Page javax.servlet.jsp.jspcontext The JSP page that creates the object. In a multithreaded server, it is possible for shared resources to be accessed concurrently. In addition to scope object attributes, shared resources include in-memory data (such as instance or class variables) and external objects such as files, database connections, and network connections. Concurrent access can arise in several situations: Multiple web components accessing objects stored in the web context. Multiple web components accessing objects stored in a session. Multiple threads within a web component accessing instance variables. A web container will typically create a thread to handle each request. If you want to ensure that a servlet instance handles only one request at a time, a servlet can implement the SingleThreadModel interface. If a servlet implements this interface, you are guaranteed that no two threads will execute concurrently in the servlet s service method. A web container can implement this guarantee by synchronizing access to a single instance of the servlet, or by maintaining a pool of web component instances and dispatching each new request to a free instance. This interface does not prevent synchronization problems that result from web components accessing shared resources such as static class variables or external objects. In addition, the Servlet 2.4 specification deprecates the SingleThreadModel interface. When resources can be accessed concurrently, they can be used in an inconsistent fashion. To prevent this, you must control the access using the synchronization techniques 9
Servlet example package lt.vu.mif.javatech.web; public class MyServlet extends HttpServlet { public void init() throws ServletException { // Initialize content public void doget (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {... // set headers and get writer response.setcontenttype("text/html"); response.setbuffersize(8192); PrintWriter out = response.getwriter();... // then write the response out.println("<html/>");... out.close(); public void doget (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {... See all possible service methods at http://docs.oracle.com/javaee/6/api/javax/servlet/http/httpservlet.html 10
Servlet Mapping web.xml <servlet> <servlet-name>myservlet</servlet-name> <servlet-path>lt.vu.mif.javatech.web.myservlet</servlet-path> </servlet> <servlet-mapping> <servlet-name>myservlet</servlet-name> <url-pattern>/enroll</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>myservlet</servlet-name> <url-pattern>/pay</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>myservlet</servlet-name> <url-pattern>/bill</url-pattern> </servlet-mapping> <listener> <listener-class>lt.vu.mif.javatech.web.mylistener</listener-class> </listener> since Servlet 3.0: @WebServlet("/enroll") public class MyServlet extends HttpServlet { @WebListener public class MyListener implements ServletContextListener { 11
Filters A filter is an object that can transform the header and content (or both) of a request or response. The main tasks that a filter can perform are as follows: Query the request and act accordingly. Block the request-and-response pair from passing any further. Modify the request headers and data. You do this by providing a customized version of the request. Modify the response headers and data. You do this by providing a customized version of the response. Interact with external resources. The filtering API is defined by the Filter, FilterChain, and FilterConfig interfaces in the javax.servlet package. The most important method in this interface is dofilter, which is passed request, response, and filter chain objects. This method can perform the following actions: Examine the request headers. Customize the request object if the filter wishes to modify request headers or data. Customize the response object if the filter wishes to modify response headers or data. Invoke the next entity in the filter chain. If the current filter is the last filter in the chain that ends with the target web component or static resource, the next entity is the resource at the end of the chain; otherwise, it is the next filter that was configured in the WAR. The filter invokes the next entity by calling the dofilter method on the chain object (passing in the request and response it was called with, or the wrapped versions it may have created). Alternatively, it can choose to block the request by not making the call to invoke the next entity. In the latter case, the filter is responsible for filling out the response. Examine response headers after it has invoked the next filter in the chain. Throw an exception to indicate an error in processing. In addition to dofilter, you must implement the init and destroy methods. The init method is called by the container when the filter is instantiated. If you wish to pass initialization parameters to the filter, you retrieve them from the FilterConfig object passed to init. 12
Filter example package lt.vu.mif.javatech.web.filter; import java.io.ioexception; import java.util.date; import javax.servlet.*; public class LogFilter implements Filter { public void dofilter(servletrequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; //Get the IP address of client machine. String ipaddress = request.getremoteaddr(); System.out.println("IP "+ipaddress + ", Time " + new Date().toString()); chain.dofilter(req, res); public void init(filterconfig config) throws ServletException { //Get init parameter String testparam = config.getinitparameter("test-param"); //Print the init parameter System.out.println("Test Param: " + testparam); public void destroy() { //add code to release any resource 13
Servlet Filter Mapping in web.xml web.xml <filter> <filter-name>logfilter</filter-name> <filter-class> lt.vu.mif.javatech.web.filter.logfilter </filter-class> <init-param> <param-name>test-param</param-name> <param-value>this parameter is for testing.</param-value> </init-param> </filter> <filter-mapping> <filter-name>logfilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>logfilter</filter-name> <servlet-name>servlet1</servlet-name> </filter-mapping> since Servlet 3.0: @WebFilter(filterName = "LogFilter", urlpatterns = "/*", initparams = { @WebInitParam(name = "test-param", value = "This parameter is for testing.") ) public class LogFilter implements Filter { 14
Session When a client visits the webapp for the first time and/or the HttpSession is to be obtained for the first time by request.getsession(), then the servletcontainer will create it, generate a long and unique ID and store it in server's memory. The servletcontainer will also set a Cookie in the HTTP response with JSESSIONID as cookie name and the unique session ID as cookie value. As per the HTTP cookie specification (a contract a decent webbrowser and webserver has to adhere), the client (the webbrowser) is required to send this cookie back in the subsequent requests as long as the cookie is valid. The servletcontainer will determine every incoming HTTP request header for the presence of the cookie with the name JSESSIONID and use its value (the session ID) to get the associated HttpSession from server's memory. The HttpSession lives until it has not been used for more than the <session-timeout> time, a setting you can specify in web.xml, which defaults to 30 minutes. So when the client doesn't visit the webapp anymore for over 30 minutes, then the servletcontainer will trash the session. Every subsequent request, even though with the cookie specified, will not have access to the same session anymore. The servletcontainer will create a new one. On the other hand, the session cookie on the client side has a default lifetime which is as long as the browser instance is running. So when the client closes the browser instance (all tabs/windows), then the session will be trashed at the client side. In a new browser instance the cookie associated with the session won't be sent anymore. A new request.getsession() would return a brand new HttpSession and set a cookie with a brand new session ID. 15
HttpSession usage public class CashierServlet extends HttpServlet { public void doget (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the user s session HttpSession session = request.getsession(); // Get session ID String id = session.getid(); // Get data ShoppingCart cart = (ShoppingCart) session.getattribute("cart"); // Determine the total price of the user s books double total = cart.gettotal(); // Invalidate the session session.invalidate(); 16
Session Management in Tomcat Session management in Tomcat is the responsibility of the session manager, defined with interface org.apache.catalina.manager. Implementations of the Manager interface manage a collection of sessions within the container. Tomcat 7 comes with several Manager implementations. Session Manager Description org.apache.catalina.session.standardmanager Default manager implementation, with limited session persistence, for a single Tomcat instance only. org.apache.catalina.session.persistentmanager Configurable session manager for session persistence on a disk or relational database. Supports session swapping and fault tolerance. 17
Servlets In a nutshell The ServletContext lives as long as the webapp lives. It's been shared among all requests in all sessions. The HttpSession lives as long as the client is interacting with the webapp with the same browser instance and the session hasn't timed out at the server side yet. It's been shared among all requests in the same session. The HttpServletRequest and HttpServletResponse lives as long as the client has sent it until the complete response (the webpage) is arrived. It is not being shared elsewhere. Any Servlet, Filter and Listener lives as long as the webapp lives. They are being shared among all requests in all sessions. Any attribute which you set in ServletContext, HttpServletRequest and HttpSession will live as long as the object in question lives. Servlets and filters are shared among all requests. That's the nice thing of Java, it's multithreaded and that different threads can make use of the same instance. It would otherwise have been too expensive to recreate it on every request. 18
Thread Safety Example public class MyServlet extends HttpServlet { private Object a; protected void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { Object b; a = request.getparameter("foo"); b = request.getparameter("foo"); 19
Servlet tips Overriding service method protected void service(httpservletrequest req, HttpServletResponse resp) throws ServletException,IOException { super.service(req, resp); Wait for long running methods to finish public void destroy() { while(numservices() > 0) { try { Thread.sleep(interval); catch (InterruptedException e) { RequestDispatcher Including Other Resources in the Response RequestDispatcher dispatcher = getservletcontext().getrequestdispatcher("/banner"); if (dispatcher!= null) dispatcher.include(request, response); Transferring Control to Another Web Component RequestDispatcher dispatcher = request.getrequestdispatcher("/template.jsp"); if (dispatcher!= null) dispatcher.forward(request, response); 20
Asynchronous Support (since Servlet 3.0) Annotation attribute @WebServlet(url="/foo" asyncsupported=true) Servlet Request Methods adds the support for asynchronous processing: startasync(servletrequest, servletresponse) startasync() getasynccontext() isasyncsupported() isasyncstarted() AsyncContext class provides the execution context for an asynchronous operation. The class provides a variety of methods that you can use to get access to the underlying request and response objects. I.e. AsyncContext.dispatch() // forwards the request back to the original URL AsyncContext.dispatch(path) // forwards the request to the path relative to the context of the request AsyncContext.dispatch(servletContext, path) // forwards the request to the path relative to the specified context AsyncContext.complete() // completes the asynchronous operation that was started Asynchronous Listener class for asynchronous processing, AsyncListener. You can use this class in an application to get notified when asynchronous processing is completed. AsyncContext ac = req.startasync(); req.addasynclistener(new AsyncListener() { public void oncomplete(asyncevent event) throws IOException {... 21
AsyncContext example @WebServlet(urlPatterns = "/dispatchexample", asyncsupported = true) public class DispatchExample extends HttpServlet { public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); AsyncContext asyncctx = request.startasync(); ServletRequest req = asyncctx.getrequest(); out.println(req.isasyncstarted()); // true if (bol) { asyncctx.dispatch("/someoutput.html"); out.println(req.isasyncstarted()); // false out.println(req.isasyncsupported()); // true 22
Web Fragments (since Servlet 3.0) A web fragment is a portion or all of the deployment descriptor(web.xml). It can be defined and enclosed in the jar file's META-INF of a framework or library. A web fragment provide logical division of the web application so that the frameworks used within the web application can specify all the artifacts without requiring developers to edit or add any info in the web.xml. It employed nearly all the elements of the deployment descriptor (web.xml). More than one web fragment can be employed. Each web fragment describe logical division. All these web fragment should be considered as complete web.xml (deployment descriptor). The web fragment provide capability to the frameworks to auto register to the web container. Following things should be keep in the mind before implementing web fragment: The web fragment must reside in a file having name web-fragment.xml. The top level descriptor in web-fragment.xml must be <web-fragment>. The web fragment must put inside framework's JAR file's META-INF directory. This jar file must placed inside the web application's WEB-INF/lib directory. The web application's deployment descriptor have a new <metadata-complete> property. If it is sets true, annotations present in application's classes, and web fragments is ignore by the deployment tool. If it sets false or not described, annotations present in application's classes, and web fragments is examine by the deployment tool. 23
web-fragment.xml example web-fragment.xml <?xml version="1.0" encoding="utf-8"?> <web-fragment xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/webapp_2_5.xsd" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-fragment_3_0.xsd" id="webappfragment_id" version="3.0"> <name>webfragment1</name> <filter> <filter-name>myfilter</filter-name> <filter-class>lt.vu.mif.javatech.web.filter.logfilter</filter-class> </filter> <filter-mapping> <filter-name>myfilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-fragment> web.xml <?xml version="1.0" encoding="utf-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/webapp_2_5.xsd" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="webapp_id" version="3.0"> <display-name>servlet3webfragment</display-name> <absolute-ordering> <name>webfragment1</name> </absolute-ordering> <listener> 24
Java Server Pages JSP docs are XML Documents containing: Fixed-Template Data (static) XHTML Components XML markup JSP Components (dynamic) The container compiles a JSP to a servlet the first time it is served. Use JSPs when ratio of FTD to Dynamic Content is high JSPs decouple design from programming JSP = HTML containing Java Servlet = Java containing HTML JSPs replace views Example: <?xml version = 1.0?> <!DOCTYPE html PUBLIC ".../xhtml1-strict.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>demo</title> </head> <body> FTD <JSP> FTD <JSP> FTD <JSP>... </body> </html> 25
JSP Internals JSP pages are actually servlets! client container The Web container translates JSP pages into Java servlet source code (.java ) Then compiles that class into Java servlet class JSP pages have the same life cycle like servlets form.jsp compile form.jsp request HTML : MyJSP Tomcat stores the compiled JSP pages in the directory $CATALINA_HOME/work 26
JSP Components Scriptlets <% %> <% (partial) statement %> <%-- comment --%> <%! declaration %> <%= expression %> Directives <%@ %> <%@ include... %> <%@ taglib... %> <%@ page errorpage = "foo.jsp" %> <%@ page session = "true" %> <%@ page language = "java" %> <%@ page extends = "java.awt.frame" %> <%@ page import = "java.util.*" %> Actions <jsp: /> <jsp:include page = "foo.jsp" flush = "true" /> <jsp:forward page = "foo.jsp /> <jsp:plugin type="applet" code="appletclass.class /> <jsp:param name = "date" value = "<%= new Date() %>" /> <jsp:usebean id="cart" scope="session" class = "CartBean" /> <jsp:getproperty name = "cart" property = "total" /> <jsp:setproperty name = "cart" property = "total" value = "200" /> 27
Predefined JSP variables JSP pages support a number of predefined variables that you can use request current HttpServletRequest response the HttpServletResponse session current HttpSession associated with the request (if any) out the text stream for the result of the JSP page (PrintWriter) application - the ServletContext as obtained via getservletconfig().getcontext(). Always use the application object in a synchronized section! page - synonym of this object (not very useful) exception - the implicit Throwable object Available only in the error pages and contains the last exception config - contains the ServletConfig for the current JSP page Useful for accessing the init parameters These variables are always initialized and can be used in any place in the JSP page Your hostname: <%=request.getremotehost() %> Session timeout: <%=session.getmaxinactiveinterval() %> Browser: <%=request.getheader("user-agent") %> 28
JSP: Action examples Include Directive vs. Action Static (html) or dynamic (jsp) files can be included <jsp:include page="foo.jsp" flush="true" /> foo.html included after each change <%@ include file="foo.jsp" %> foo.html included once at compile time Forward with parameter <jsp:forward page="foo.jsp"> <jsp:param name="date value="<%= new Date() %>"/> </jsp:forward> Bean Usage <jsp:usebean id = "helper" scope = "session" class = "ViewHelper" /> <% String command = request.getparameter("cmd"); String content = helper.execute(command); %> <p> result = <%= content %> </p> 29
JSP: custom Action (aka Tag) Example custom tag: <%@ taglib prefix="ex" uri="web-inf/custom.tld"%> <html> <body> <ex:note author= Vardas"> JSP labai smagu programuoti! </ex:note> </body> </html> Tag library at WEB-INF/custom.tld <taglib> <tlib-version>1.0</tlib-version> <jsp-version>2.0</jsp-version> <short-name>example TLD</short-name> <tag> <name>note</name> <tag-class>lt.vu.mif.javatech.web.notetag</tag-class> <body-content>scriptless</body-content> <attribute> <name>author</name> </attribute> </tag> </taglib> 30
JSP: custom Action (aka Tag) handler package lt.vu.mif.javatech.web; import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*; import java.io.*; public class NoteTag extends SimpleTagSupport { private String author; public void setauthor(string author) { this. author = author; public void dotag() throws JspException, IOException { StringWriter sw = new StringWriter(); JspWriter out = getjspcontext().getout(); out.println( Author: + author + </br> ); out.println( Note: ); getjspbody().invoke(sw); out.println(sw.tostring()); 31
JSP: escaping Escaping problems are very common in the Web programming Displaying not escaped text is dangerous Makes the application unstable Opens security vulnerabilities When displaying text it should not contain any HTML special characters Performing escaping of the HTML entities is obligatory! Consider the following JSP page: <html> You entered: <%= request.getparameter("something") %> <form> Enter something:<br> <input type="text" name="something"> <input type="submit"> </form> </html> What will happen if we enter this? <script language="javascript">alert('bug!');</script> 32
JSP Standard Tag Library (JSTL) The JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP tags which encapsulates core functionality common to many JSP applications. JSR 52: A Standard Tag Library for JavaServer Pages at http://www.jcp.org/en/jsr/detail?id=52 Setup: Download the binary distribution from Apache Standard Taglib and unpack the compressed file. To use the Standard Taglib from its Jakarta Taglibs distribution, simply copy the JAR files in the distribution's 'lib' directory to your application's webapps\root\web-inf\lib directory. Include JSTL library in your JSP, i.e. core: <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> JSTL tags: Core Tags Formatting tags The JSTL formatting tags are used to format and display text, the date, the time, and numbers for internationalized Web sites. SQL tags The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs) such as Oracle, mysql, or Microsoft SQL Server. XML tags The JSTL XML tags provide a JSP-centric way of creating and manipulating XML documents. JSTL Functions JSTL includes a number of standard functions, most of which are common string manipulation functions. 33
JSTL Core tags <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> Tag <c:out > <c:set > <c:remove > <c:catch> <c:if> Description Like <%=... >, but for expressions. Sets the result of an expression evaluation in a 'scope' Removes a scoped variable (from a particular scope, if specified). Catches any Throwable that occurs in its body and optionally exposes it. Simple conditional tag which evalutes its body if the supplied condition is true. <c:choose> Simple conditional tag that establishes a context for mutually exclusive conditional operations, marked by <when> and <otherwise> <c:when> Subtag of <choose> that includes its body if its condition evalutes to 'true'. <c:otherwise > Subtag of <choose> that follows <when> tags and runs only if all of the prior conditions evaluated to 'false'. <c:import> Retrieves an absolute or relative URL and exposes its contents to either the page, a String in 'var', or a Reader in 'varreader'. <c:foreach > The basic iteration tag, accepting many different collection types and supporting subsetting and other functionality. <c:fortokens> Iterates over tokens, separated by the supplied delimeters. <c:param> Adds a parameter to a containing 'import' tag's URL. <c:redirect > Redirects to a new URL. <c:url> Creates a URL with optional query parameters 34
Generated servlet example (1) package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class index_jsp extends org.apache.jasper.runtime.httpjspbase implements org.apache.jasper.runtime.jspsourcedependent { private static final javax.servlet.jsp.jspfactory _jspxfactory = javax.servlet.jsp.jspfactory.getdefaultfactory(); private static java.util.map<java.lang.string,java.lang.long> _jspx_dependants; private javax.el.expressionfactory _el_expressionfactory; private org.apache.tomcat.instancemanager _jsp_instancemanager; public java.util.map<java.lang.string,java.lang.long> getdependants() { return _jspx_dependants; public void _jspinit() { _el_expressionfactory = _jspxfactory.getjspapplicationcontext(getservletconfig().getservletcontext()).getexpressionfactory(); _jsp_instancemanager = org.apache.jasper.runtime.instancemanagerfactory.getinstancemanager(getservletconfig()); public void _jspdestroy() { public void _jspservice(final javax.servlet.http.httpservletrequest request, final javax.servlet.http.httpservletresponse response) throws java.io.ioexception, javax.servlet.servletexception { final javax.servlet.jsp.pagecontext pagecontext; javax.servlet.http.httpsession session = null; final javax.servlet.servletcontext application; final javax.servlet.servletconfig config; javax.servlet.jsp.jspwriter out = null; final java.lang.object page = this; javax.servlet.jsp.jspwriter _jspx_out = null; javax.servlet.jsp.pagecontext _jspx_page_context = null; 35
Generated servlet example (2) try { response.setcontenttype("text/html"); pagecontext = _jspxfactory.getpagecontext(this, request, response, null, true, 8192, true); _jspx_page_context = pagecontext; application = pagecontext.getservletcontext(); config = pagecontext.getservletconfig(); session = pagecontext.getsession(); out = pagecontext.getout(); _jspx_out = out; out.write("<html>\r\n"); out.write("\tyou entered: "); out.print( request.getparameter("something") ); out.write("\r\n"); out.write("\t<form>\r\n"); out.write("\t\tenter something:<br>\r\n"); out.write("\t\t<input type=\"text\" name=\"something\">\r\n"); out.write("\t\t<input type=\"submit\">\r\n"); out.write("\t</form>\r\n"); out.write("</html>\r\n"); catch (java.lang.throwable t) { if (!(t instanceof javax.servlet.jsp.skippageexception)){ out = _jspx_out; if (out!= null && out.getbuffersize()!= 0) try { out.clearbuffer(); catch (java.io.ioexception e) { if (_jspx_page_context!= null) _jspx_page_context.handlepageexception(t); finally { _jspxfactory.releasepagecontext(_jspx_page_context); 36
Session Conclusions Hopefully you have learned something new with old vanilla Java Web technologies: Servlets and JSPs You now must be able to start a better grounded Web programming with Java 37