~~SLIDESHOW~~ ====== Presentation-tier Services ====== * Server services is the largest market sector in Java world((Mobile may well become more important, certainly in terms of installed systems, if not in terms of monetary value, we shall see)). * In this lecture we shall examine two technologies that are part of the web container services that the Java EE platform offers: * Server-hosted Java applications: Servlets which process HTTP requests. * Java Server Pages JSP: a servlet-based document delivery technology similar to Microsoft’s ASP. * Servlet examples use the Jakarta/Tomcat servlet engine in "standalone" mode. ----- The slides and notes in this presentation are adapted from //Groovy Programming//, //Groovy in Action// and //Thinking in Java// (See [[lecture0#Reading|Recommended Reading]]). An index to the source code for all the examples in this lecture is [[/~eechris/at-m42/Examples/lecture13|available]]. ===== Importance of the Server ===== * Some estimates state that half of worldwide software development involves client/server applications. * Despite best efforts of some, server is not a single source platform (e.g. WinTel): much more heterogeneous than the typical client (Desktop). * The Java platform offers platform-independent server environment with developing support that allow links to “legacy” applications. * Possibly most important server application is ability to link to an SQL database: this is provided in Java by the JDBC package (see [[lecture14|Integration Tier Services]]). * Next most important is web services providing (browser based) thin-client applications for e-commerce, in institutions via the intranet and to the general public via the Internet. ===== Presentation Tier Services ===== Form depends on architecture (see [[lecture12#architecture|previous lecture]]) * //Thick-Client Application// may provide user interface in Swing and talk directly to business tier objects using RMI (3 tier) or to a database using JDBC (2 tier). * //Applet// is downloaded from a server as an object in a web page and may communicate with its home server using either standard sockets or HTTP. * //Thin-Client// needs to get all its information in the form of client-side browser technologies HTML/CSS/JavaScript and speaks to a web container in HTTP. * Most popular application delivery method for Java EE is via a web container. Thin client model is most often used despite being one of the most challenging applications to program! ===== Lecture Contents ===== * **[[#Servlets and Groovlets]]** * [[#Java Server Pages]] * [[#Web Designers Want Templates Not Code!]] * [[#Groovy Server Pages]] * [[#Architectural Issues: Patterns|Architectural issues to be aware of!]] ===== Servlets ===== * Client access from the Internet or corporate intranets is a sure way to allow many users to access data and resources easily. * This type of access is based on clients using the World Wide Web standards of Hypertext Markup Language (HTML) and Hypertext Transfer Protocol (HTTP). * The //Servlet API// abstracts a common solution framework for responding to HTTP requests. * Servlets also provide a simpler API for handling server-side of a general client-server application than sockets. ===== CGI Processing ===== {{:at-m42:cgi.png?525 |CGI processing: activity diagram.}} * Can be done with any program that can read standard input, standard output and environment variables. E.g. C, C++, Perl, Python (even Java and Groovy). * Note that CGI script, and associated process (if any) has to be loaded for each request. ===== Servlet Processing ===== {{:at-m42:servlet.png?538|Servlet processing: activity diagam}} ===== Client/Server in Java ===== * It might be ideal to go to a completely Java-based solution to this problem -- an applet on the client side to validate and send the data, and a servlet on the server side to receive and process the data. * Unfortunately you cannot rely on a particular version of Java being available on a client’s Web browser; in fact, you can’t rely on a Web browser supporting Java at all! * On an intranet this may not be a problem: you have control of what is on desktop. * On the Web the safest approach is to handle all the processing on the server side and deliver plain HTML to the client. * That way, no client will be denied the use of your site because they do not have the proper software installed. ===== Advantages of Servlets ===== * Servlets provide an excellent solution for server-side programming support * They are one of the most popular reasons for moving to the Java Platform. * They provide a framework that replaces CGI programming * All your code has the platform portability gained from using the Java Platform. * You have access to all the Java APIs (except, of course, the ones that produce GUIs, like Swing). * You can program Servlets in Groovy! ===== The basic servlet ===== * The architecture of the servlet API is that of a classic service provider * ''service( )'' method through which all client requests will be sent by the servlet container software, * life cycle methods ''init( )'' and ''destroy( )'', which are called only when the servlet is loaded and unloaded (this happens rarely). {{:at-m42:servlet-api.png|The servlet API}} ===== … the basic servlet ===== ^ Methods and Classes ^ Descripton ^ | ''getServletConfig( )'' | returns a ''ServletConfig'' object that contains initialization and start up parameters for this servlet. | | ''getServletInfo( )'' | returns a ''String'' containing information about the servlet, such as author, version, and copyright. | | ''class GenericServlet'' | A shell implementation of this interface and is typically not used. | | ''class HttpServlet'' | An extension of ''GenericServlet'' and is designed specifically to handle the HTTP protocol. | The most convenient attribute of the servlet API is the auxiliary objects that come along with the ''HttpServlet'' class to support it. For ''HttpServlet'' class these two object are extended for HTTP: ''HttpServletRequest'' and ''HttpServletResponse''. ===== Writing Servlets in Java ===== * Subclass ''javax.servlet.http.HttpServlet'' and override ''doGet'' and/or ''doPost'' * Both methods have ''HttpServletRequest'' and ''HttpServletResponse'' parameters. * ''HttpServletRequest'' represents the request from the client. * ''HttpServletResponse'' represents the result returned by the server. ===== Hello world in Java ===== * A Servlet: (run http://localhost:8080/at-m42-examples/helloServlet) extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/HelloServlet.java ---- Deploying this servlet: need to include ''servlets-api.jar'' from ''%TOMCAT_HOME%\lib'' in the compiler classpath, then compile the servlet: > javac HelloServlet.java -cp %TOMCAT_HOME%\lib\servlet-api.jar -d WEB-INF\classes Add the following to ''WEB-INF\web.xml'': ... HelloServlet uk.ac.swan.atm42.web.HelloServlet HelloServlet /helloServlet ... An sample is provided in the examples for this lecture. Just take ''at-m42\Examples\lecture13\web'', drop it into your Java web server's web apps folder (e.g. ''%TOMCAT_HOME%\webapps''), rename it to //at-m42-examples// and add ''groovy-all-1.6.0.jar'' from the ''%GROOVY_HOME%\embeddable'' to //at-m42-examples\WEB-INF\lib//. A windows //batch// file ''deploy.bat'' is provided. Edit this to set ''%JAVA_HOME%'', ''%TOMCAT_HOME%'' and ''%GROOVY_HOME%'' to suit your local settings. ===== Writing Servlets in Groovy ===== * Groovy provides the Groovelet framework which simplifies the development of servlets. * You do not need to subclass ''doGet'' or ''doPost'': standard output is simply passed to the client! ===== Hello world ===== * A Groovlet: (run http://localhost:8080/at-m42-examples/helloGroovlet.groovy) extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/helloGroovlet.groovy ===== Deployment ===== Need to tell the servlet how to handle Groovelets. This is done with web.xml((The actual configuration of a web application framework, e.g Tomcat, is outside the scope of this lecture. See http://groovy.codehaus.org/Groovlets for more explanation.)): Groovy groovy.servlet.GroovyServlet Groovy *.groovy ===== Implicit Groovlet Variables ===== ^ variable name ^ Note ^ Example usage ^ | ''headers'' | Map of HTTP request headers | ''headers.host'' | | ''params'' | Map of HTTP request paramters | ''params.myParam'' | | ''session'' | ''Servletsession'', can be ''null'' | ''session?.mySavedParam'' | | ''request'' | ''HttpServletRequest'' | ''request.remoteHost'' | | ''response'' | ''HttpServletResponse'' | ''%%response.contentType='text/html'%%'' | | ''context'' | ''ServletContext'' | ''context.myParam'' | | ''application'' | ''ServletContext'' (same as context) | ''application.myParam'' | | ''out'' | ''response.writer'' | Lazy initialization, not in binding | | ''sout'' | ''response.outputStream'' | Lazy initialization, not in binding | | ''html'' | HTML builder initialized as ''new MarkupBuilder(out)'' | Lazy initialization, not in binding | ---- Lazy initialization means that the associated variable is ''null'' unless your application uses it. This allows us to work on the ''response'' object before the output stream is opened. For example this is necessary to set reponse properties such as ''contentType'', set a cookie or initialize a session. ===== Implicit Variables ===== Using ''getServerInfo'' and ''getInitParameter'': (run http://localhost:8080/at-m42-examples/implicitVariables.groovy) extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/implicitVariables.groovy ===== Specify Init Parameters ===== ... lecturer Dr Chris P. Jobling module AT-M42 ===== Using a Builder to Groovy-fy HTML Generation ===== * Using a builder: (run http://localhost:8080/at-m42-examples/implicitVariables2.groovy) extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/implicitVariables2.groovy ---- A problem with many server-side processing systems which persists in many server-side systems, from CGI-scripts in Perl through to Java and Groovy servlets, is that HTML ends up being produced in print statements which is far from ideal. For one thing, programmers are not web developers and web developers are not programmers. Mixing code with mark-up in this way fails to affectively separate the concerns of the programmer and the web developer. Groovy provides a coding pattern called a //builder// that can be used to construct many different kinds of hierarchical data structure. One such builder is the XML Markup Builder (''groovy.xml.MarkupBuilder'') which in this slide has been used to create the HTML from the previous example programmatically. Notice how the judicious use of functions, closures and indentation, has been exploited to make the generation of the HTML programmer friendly. We shall see later that GSP does the same thing for web developers. You should also note that the builder ''html'' is an implicit variable that automatically is provided by the Groovlet system. ===== The Groovlet Binding ===== * [[http://localhost:8080/at-m42-examples/inspect.groovy|inspect.groovy]]: extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/inspect.groovy ---- You can examine the variables that are passed to a Groovlet by the ''GroovyServlet'' that handles the request. This can be useful information when you need to debug a Groovlet or forget what a bound variable is called. Example 5 is a simple groovlet that displays this information. ===== Handling forms data ===== * Whenever a form is submitted to a servlet, the ''HttpServletRequest'' (Groovlet implicit variable ''request'') comes preloaded with all the form data, stored as key-value pairs. * If you know the names of the fields, you can just use them directly with the ''getParameter( )'' method to look up the values. You can also get an ''Enumeration'' (old form of Java iterator) of the field names. * The following example also demonstrates how a single Groovlet can be used to produce the page that contains the form, and to respond to the page. * If the List is empty, there are no fields; this means no form was submitted; the form is produced, and the submit button will re-call the same servlet. * If fields do exist they are displayed. ===== Handling Form Data ===== * Handling form data : (run http://localhost:8080/at-m42-examples/echoForm.groovy) extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/echoForm.groovy ===== Thread-safe servlets ===== * The servlet container has a pool of threads that it will dispatch to handle client requests. * It is quite likely that two clients arriving at the same time could be processing through your ''service( )'' at the same time. * Therefore the ''service()'' method must be written in a thread-safe manner. * Any access to common resources (files, databases) will need to be guarded by using the ''synchronized'' keyword. ===== Handling sessions with servlets ===== * HTTP is a "sessionless" protocol, so you cannot tell from one server hit to another if you've got the same person repeatedly querying your site, or if it is a completely different person. * A great deal of effort has gone into mechanisms that will allow Web developers to track sessions. * Companies could not do e-commerce without keeping track of a client and the items they have put into their shopping cart, for example. * There are several methods of session tracking, but the most common method is with persistent "cookies." ===== What's a cookie? ===== * The HTTP Working Group of the Internet Engineering Task Force has written cookies into the official standard in [[http://www.isi.edu/in-notes/rfc2109.txt|RFC 2109]]. * A cookie is nothing more than a small piece of information sent by a Web server to a browser. * The browser stores the cookie on the local disk, * Whenever another call is made to the URL that the cookie is associated with, the cookie is quietly sent along with the call. * This provides a way that the server can be told that it's you calling. ===== Can't Rely on Cookies ===== * Clients can, however, turn off the browser’s ability to accept cookies * If your site must track a client who has turned off cookies, you have a problem since the session tracking capabilities of the servlet API are designed around cookies. * Other means of session tracking include URL rewriting (popular on search engines) or hidden form fields. These have to coded by hand. No built-in support from servlet API. ===== The Cookie class ===== * The servlet API (version 2.0 and up) provides the ''Cookie'' class. To use a cookie you simply add it to the response object. * The constructor takes a cookie name as the first argument and a value as the second. * Cookies are added to the response object before you send any content. def oreo = new Cookie("AT-M42", "2009"); response.addCookie(cookie); * Cookies are recovered by calling the ''getCookies( )'' method of the ''HttpServletRequest'' object, which returns an list of cookie objects. def cookies = request.getCookies(); * Call ''getValue()'' for each cookie, to produce a ''String'' containing the cookie contents. ''getValue("AT-M42")'' will produce a ''String'' containing "2009." ===== What’s a Session? ===== * A session is one or more page requests by a client to a Web site during a defined period of time. * If you buy groceries on-line, for example, you want a session to be confined to the period from when you first add an item to "my shopping cart" to the point where you check out((This might be a long time!)). * Each item you add to the shopping cart will result in a new HTTP connection, which has no knowledge of previous connections or items in the shopping cart. * To compensate for this lack of information, the mechanics supplied by the cookie specification allow your servlet to perform session tracking. ===== Session Class ===== * A servlet ''Session'' object lives on the server side of the communication channel; it captures useful data about the client as it moves through and interacts with your Web site. * This data may be pertinent for the present session, such as items in the shopping cart, or it may be data such as authentication information that was entered when the client first entered your Web site, and which should not have to be re-entered during a particular set of transactions. * The ''Session'' class of the servlet API uses the ''Cookie'' class to do its work. * All the Session object needs is some kind of unique identifier stored on the client and passed to the server. * [[http://localhost:8080/at-m42-examples/sessionPeek.groovy|Example 7]] (see notes) implements session tracking with the servlet API. ---- * [[http://localhost:8080/at-m42-examples/inspect.groovy|sessionPeek.groovy]]: extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/sessionPeek.groovy ===== Lecture Contents ===== * [[#Servlets and Groovlets]] * **[[#Java Server Pages]]** * [[#Web Designers Want Templates Not Code!]] * [[#Groovy Server Pages]] * [[#Architectural Issues: Patterns|Architectural issues to be aware of!]] ===== Java Server Pages ===== * Java Server Pages (JSP) is a standard Java extension that is defined on top of the servlet API. * The goal of JSPs is the simplified creation and management of dynamic Web pages. * The Tomcat reference implementation from tomcat.apache.org automatically supports JSPs. * JSPs allow you to combine the HTML of a Web page with pieces of Java code in the same document. ===== Lifecycle of a JSP (1) ===== * Java code is surrounded by special tags that tell the JSP container that it should use the code to generate a servlet, or part of one. * The benefit of JSPs is that you can maintain a single document that represents both the page and the Java code that enables it. * The downside is that the maintainer of the JSP page must be skilled in both HTML and Java. * The first time a JSP is loaded by the JSP container the servlet code necessary to fulfil the JSP tags is automatically generated, compiled, and loaded into the servlet container. * The static portions of the HTML page are produced by sending ''static String'' objects to ''write()''. The dynamic portions are included directly into the servlet. ===== Lifecycle of a JSP (2) ===== * As long as the JSP source for the page is not modified, it behaves as if it were a static HTML page with associated servlets. * If you modify the source code for the JSP, it is automatically recompiled and reloaded the next time that page is requested. * Dynamism means that you’ll see a slow response for the first-time access to a JSP. * However, since a JSP is usually used much more than it is changed, you will normally not be affected by this delay. ===== The structure of a JSP page ===== * A cross between a servlet and an HTML page. * All JSP tags are denoted by: ''<%'' JSP code here ''%>'' The leading percent sign may be followed by other characters that determine the precise type of JSP code in the tag. ===== Simple JSP ===== * Here’s an extremely simple JSP example ([[http://localhost:8080/at-m42-examples/ShowSeconds.jsp|ShowSeconds.jsp]]): extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/ShowSeconds.jsp ===== Implicit Objects ===== ^Implicit variable^Of Type (''javax.servlet'')^Description^Scope^ |''request''|protocol dependent subtype of ''HttpServletRequest''|The request that triggers the service invocation.|request| |''response''|protocol dependent subtype of ''HttpServletResponse''|The response to the request.|page| |''pageContext''|''jsp.PageContext''|The page context encapsulates implementation-dependent features and provides convenience methods and namespace access for this JSP.|page| |''session''|protocol dependent subtype of ''http.HttpSession''|The session object created for the requesting client. See servlet Session object.|session| |''application''|''ServletContext''|The servlet context obtained from the servlet configuration object (e.g., ''getServletConfig()'', ''getContext()''.|application| ===== Implicit Objects … cont. ===== ^Implicit variable^Of Type (''javax.servlet'')^Description^Scope^ |''out''|''jsp.JspWriter''|The object that writes into the output stream.|page| |''config''|''ServletConfig''|The ''ServletConfig'' for this JSP.|page| |''page''|''java.lang.Object''|The instance of this page's implementation class processing the current request.|page| ---- Meaning of "scope": * ''page'' object has a scope that is restricted to the JSP. * ''session'' object has a scope that exceeds that of a page: may span several client requests and pages. * ''application'' object can provide services to a group of JSP pages that together represent a Web application. ===== JSP Directives ===== * Communicate with servlet container. No output. General form: <%@ directive {attr="value"}* %> * Examples of "page" directives: <%@ page language="java" %> <%@ page session="java" import="java.util.*" %> * Other page directive attributes: ''language'', ''extends'', ''import'', ''session'', ''buffer'', ''autoFlush'', ''isThreadSafe'', ''info'' and ''errorPage''. ===== JSP Scripting Elements ===== There are three types: declarations, scriptlets and expressions. * Declaration: ''<%! //Declaration// %>'': define a variable * Scriptlet: ''<% //scriptlet// %>'': fragment of java code * Expression: ''<%= //expression// %>'': evaluate expression and output result + two types of comments: ''<%-- //jsp comment// --%>'', and '' '' ===== JSP Examples ===== * Example 9: Hello world JSP [[http://localhost:8080/at-m42-examples/Hello.jsp|Hello.jsp]] ([[http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/Hello.jsp|source]] listing in notes) * Example 10: Extracting fields and values [[http://localhost:8080/at-m42-examples/DisplayFormData.jsp|DisplayFormData.jsp]] ([[http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/DisplayFormData.jsp|source]] listing in notes) * Example 11: JSP page attributes and scope [[http://localhost:8080/at-m42-examples/Scope.jsp|Scope.jsp]] ([[http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/Scope.jsp|source]] listing in notes) * Example 12: Manipulating sessions in JSP [[http://localhost:8080/at-m42-examples/SessionObject.jsp|SessionObject.jsp]] ([[http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/SessionObject.jsp|source]] listing in notes) * Example 13: Creating and Modifying Cookies [[http://localhost:8080/at-m42-examples/Cookies.jsp|Cookies.jsp]] ([[http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/Cookies.jsp|source]] listing in notes) ---- **Example 9**: Hello world JSP extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/Hello.jsp **Example 10**: Extracting fields and values This JSP also generates the form: extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/DisplayFormData.jsp **Example 11**: JSP page attributes and scope extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/Scope.jsp **Example 12**: Manipulating sessions in JSP extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/SessionObject.jsp **Example 13**: Creating and Modifying Cookies extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/Cookies.jsp ===== Lecture Contents ===== * [[#Servlets and Groovlets]] * [[#Java Server Pages]] * **[[#Web Designers Want Templates Not Code!]]** * [[#Groovy Server Pages]] * [[#Architectural Issues: Patterns|Architectural issues to be aware of!]] ===== Templates Not Code! ===== * You’ll have noticed that the Servlet/JSP programming model is far from ideal * Suits no-one! * Web designers work in HTML, not Java! * Programmers work in code, not HTML! * Mixing code and markup up is error prone and does not separate concerns. * Recognising this, common pattern is to put code into helper applications and embed a simpler "templating" language into the HTML. * Pattern //Template View//((See Fowler Patterns of Enterprise Application Architecture [[http://www.martinfowler.com/eaaCatalog/templateView.html|Template View]])) -- renders information into HTML by embedding markers in an HTML page. ---- **Notes** Far from ideal models: * Servlets: //HTML markup// embedded in print statements * Groovlets: HTML markup //produced// by //arcane code constructs// ... better for programmer, s/he still needs to know HTML! * JSP: //Java code// embedded in HTML bad for web developers and dangerous -- bad Java code leads to difficult to debug errors that only manifest themselves at run-time and can only be debugged from server log files. ===== Groovy Server Pages ===== * A possible implementation of the //Template View// pattern: * Groovy has simpler syntax than Java so less of a problem * Syntactically more forgiving * Separation of concerns: * can use Groovlet as a //controller// and static Groovy Server Page (GSP) as a //view//. * web designer can work with view code (mostly HTML with simplified //view logic//) * application developer can work with application logic in the controller. * Good compromise between code-only servlet and Java-rich JSP. ===== Another example ===== * Example from //Groovy in Action//: [[http://localhost:8080/at-m42-examples/HighLow.groovy|HighLow.groovy]]. * This is the //controller//: def session = request.session def guess = params.guess guess = guess ? guess.toInteger() : null if (params.restart) guess = null if (! session.goal || params.restart) { session.goal = (Math.random() * 100).toInteger() } def goal = session.goal // ... ===== Example (continued) ===== // ... html.html { head { title 'Think of a Number' } body { h1 'Think of a Number' if (goal && guess) { div "Your guess is $guess " if (guess == goal) { div 'correct!' } else if (guess < goal) { div 'too low' } else { div 'too high' } } p "What's your guess (0..100)?" form(action : 'HighLow.groovy') { input (type : 'text', name : 'guess', '') button (type : 'submit', 'Guess') button (type : 'submit', name : 'restart', value : 'true', 'New Game') } } } ===== Adding GSP capabilities to Servlet container ===== Groovy Server Pages groovy.template.TemplateServlet Groovy Server Pages *.gsp ===== A GSP View Page ===== extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/HighLow.gsp ===== The Controller: Dispatches to View ===== * Revised controller Groovlet: [[http://localhost:8080/at-m42-examples/HighLow.groovy|HighLow2.groovy]]. extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/HighLow2.groovy ===== Other Examples of Template View implementations ===== * Not for discussion here. * Java standard is to use "custom tags" that talk to Java classes. * Tags look like XML tags (with namespaces) in (X)HTML pages. * JSTL -- Java Standard Tag Library provides access to beans and provides simple programming logic tags. * Can eliminate ''<% … %>'' from JSP code! * Several open source alternatives: * Best regarded seems to be //[[http://velocity.apache.org/|Velocity]]// (another Apache project) * Very simple template language embedded in HTML -- similar to GSP * Parsed and replaced by computational results (by a special Servlet) at access time. * Transparent to web developers who just see HTML pages. ===== Lecture Contents ===== * [[#Servlets and Groovlets]] * [[#Java Server Pages]] * [[#Web Designers Want Templates Not Code!]] * [[#Groovy Server Pages]] * **[[#Architectural Issues: Patterns|Architectural issues to be aware of!]]** ===== Architectural Issues: Patterns ===== * Web container gets its requests from a web client in HTTP and returns HTML views of the application's business objects. * Business objects are Java objects in the //business tier//. * //Web Tier// communicates with the //Business Tier// either using some form of distributed computing technique or directly via Java/Groovy objects. * Many presentation layer patterns are designed to simplify (or at least manage) the difficulties inherent with the "//impedance mismatch//" in this model. * Also allow web designers and programmers to do their things without stepping on each others toes. ===== Web Tier as “Model View Controller” ====== {{ :at-m42:classic-mvc.png|Model-View-Controller pattern}} * Web Tier is essentially a good example of the classic [[wp>Model-view-controller|model-view-controller]] (MVC) pattern. * Principles: * Separation of presentation from model * Separation of controller from the view * In "Web Tier" * View is HTML or [G/J]SP page. * Controller is a Servlet. * Model is a (business) object. ===== MVC Patterns in the Web Tier (1) ===== [[http://www.martinfowler.com/eaaCatalog/pageController.html|Page Controller]] -- //an object that handles a request for a specific page or action on a web site//. {{:at-m42:page-controller.png |Page controller}} * Decode URL and extract any form data * Create and invoke any model objects to process the data. * Pass data to model (models don’t need to know about HTTP) * Determine which view should display the result and forward model info to view (template page). ===== MVC Patterns in the Web Tier (2) ===== [[http://www.martinfowler.com/eaaCatalog/frontController.html|Front Controller]] -- //handles all requests for a web site//. * Used when navigation and application logic is more complex than can be reasonably handled by a collection of page controllers. {{:at-m42:front-controller1.png |Front controller (class diagram)}} {{ :at-m42:front-controller2.png|Front controller (activity diagram)}} ===== Component Model ===== Pattern is based on "components" and events {{:at-m42:component.png?654|Component model}} ===== Patterns in the Web Tier ===== * Implementing complex presentation logic in HTML is a complex task * Most of the Java EE Core Patterns are concerned with the presentation tier. * See full catalogue ([[http://java.sun.com/blueprints/corej2eepatterns/Patterns/|online]]). ===== MVC Frameworks ===== * Many common problems (as indicated by the large number of patterns for presentation tier) have been solved many times. * Many frameworks have been developed to simplify and standardise web tier development and implement the patterns. * All based around Servlets. Some also use or extend JSP. ===== Some Example Frameworks ===== //Front Controller//: * Apache Struts: http://struts.apache.org/ * Spring MVC: http://www.springframework.org/ //Component model//: * Apache Tapestry: http://tapestry.apache.org/ * Java EE JavaServer Faces (JSF): http://java.sun.com/javaee/javaserverfaces/ * Google Web Toolkit (GWT): http://code.google.com/webtoolkit/ Many more [[http://java-source.net/open-source/web-frameworks|listed here]]. ===== Lecture Summary ===== * Advantage of Java web container is that it is platform independent: will work on any machine that has a network connection and a JVM. * We have introduced some of the Java APIs that can be used to create web-based presentation services with Java. * Servlets provide a way to create applications that communicate to a client via a web browser. * JSP allows the embedding of Java code inside an HTML page. * Groovy makes both Servlets (Groovlets) and Templates (GSP) easier. * In the thin-client world you are not working alone: * Several core Java EE design patterns record best practice and have been implemented in open source and official Java solutions. ---- [[Home]] | [[lecture12|Previous Lecture]] | [[Lectures]] | [[lecture14|Next Lecture]]