Table of Contents

~~SLIDESHOW~~

Presentation-tier Services


The slides and notes in this presentation are adapted from Groovy Programming, Groovy in Action and Thinking in Java (See Recommended Reading).

An index to the source code for all the examples in this lecture is available.

Importance of the Server

Presentation Tier Services

Form depends on architecture (see previous lecture)

Lecture Contents

Servlets

CGI Processing

CGI processing: activity diagram.

Servlet Processing

Servlet processing: activity diagam

Client/Server in Java

Advantages of Servlets

The basic servlet

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

Hello world in Java

1|Example 1: A servlet in Java (at-m42/Examples/lecture13/web/HelloServlet.java)
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: <cli prompt='>'>

javac HelloServlet.java -cp %TOMCAT_HOME%\lib\servlet-api.jar -d WEB-INF\classes

</cli> Add the following to WEB-INF\web.xml:

<web-app> 
 
  ...
 
  <servlet>
  	<servlet-name>HelloServlet</servlet-name>
  	<servlet-class>uk.ac.swan.atm42.web.HelloServlet</servlet-class>	
  </servlet>	
 
  <servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
     <url-pattern>/helloServlet</url-pattern>
  </servlet-mapping>
 
  ...
 
</web-app>

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

Hello world

1|Example 2: hello world (at-m42/Examples/lecture13/web/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.xml2):

<web-app> 
 
  <servlet>
    <servlet-name>Groovy</servlet-name>
    <servlet-class>groovy.servlet.GroovyServlet</servlet-class>
  </servlet>
 
  <servlet-mapping>
    <servlet-name>Groovy</servlet-name>
      <url-pattern>*.groovy</url-pattern>
  </servlet-mapping>
 
</web-app>

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)

1|Example 3: implicit variables (at-m42/Examples/lecture13/web/implicitVariables.groovy)
extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/implicitVariables.groovy

Specify Init Parameters

<web-app> 
 
  ...
 
  <context-param>
  	<param-name>lecturer</param-name>
  	<param-value>Dr Chris P. Jobling</param-value>
  </context-param>
 
  <context-param>
  	<param-name>module</param-name>
  	<param-value>AT-M42</param-value>
  </context-param>
 
</web-app>

Using a Builder to Groovy-fy HTML Generation

1|Example 4: using a builder to avoid long print statements (at-m42/Examples/lecture13/web/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

1|Example 5: Groovlet that reveals what's in the Groovlet binding (at-m42/Examples/lecture13/web/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

Handling Form Data

1|Example 6: dumps the name-value pairs of an HTML form (at-m42/Examples/lecture13/web/echoForm.groovy)
extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/echoForm.groovy

Thread-safe servlets

Handling sessions with servlets

Can't Rely on Cookies

def oreo = new Cookie("AT-M42", "2009");
response.addCookie(cookie);
def cookies = request.getCookies(); 

What’s a Session?

Session Class

—-

1|Example 7: Using the HttpSession class (at-m42/Examples/lecture13/web/sessionPeek.groovy)
extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/sessionPeek.groovy

Lecture Contents

Java Server Pages

Lifecycle of a JSP (1)

Lifecycle of a JSP (2)

The structure of a JSP page

<% 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

1|Example 8: a simple JSP page (at-m42/Examples/lecture13/web/ShowSeconds.jsp)
extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/ShowSeconds.jsp

Implicit Objects

Implicit variableOf Type (javax.servlet)DescriptionScope
requestprotocol dependent subtype of HttpServletRequestThe request that triggers the service invocation.request
responseprotocol dependent subtype of HttpServletResponseThe response to the request.page
pageContextjsp.PageContextThe page context encapsulates implementation-dependent features and provides convenience methods and namespace access for this JSP.page
sessionprotocol dependent subtype of http.HttpSessionThe session object created for the requesting client. See servlet Session object.session
applicationServletContextThe servlet context obtained from the servlet configuration object (e.g., getServletConfig(), getContext().application

Implicit Objects … cont.

Implicit variableOf Type (javax.servlet)DescriptionScope
outjsp.JspWriterThe object that writes into the output stream.page
configServletConfigThe ServletConfig for this JSP.page
pagejava.lang.ObjectThe instance of this page's implementation class processing the current request.page

Meaning of “scope”:

JSP Directives

<%@ directive {attr="value"}* %>
<%@ page language="java" %>
<%@ page session="java" import="java.util.*" %>

JSP Scripting Elements

There are three types: declarations, scriptlets and expressions.

+ two types of comments: <%– jsp comment –%>, and <!– html comment –>

JSP Examples


Example 9: Hello world JSP

1| Example 9 hello world JSP (at-m42/Examples/lecture13/web/Hello.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:

1| Example 10: Extracting fields and values (at-m42/Examples/lecture13/web/DisplayFormData.jsp)
extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/DisplayFormData.jsp

Example 11: JSP page attributes and scope

1| Example 11: JSP page attributes and scope (at-m42/Examples/lecture13/web/Scope.jsp)
extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/Scope.jsp

Example 12: Manipulating sessions in JSP

1| Example 12: JSP page attributes and scope (at-m42/Examples/lecture13/web/SessionObject.jsp)
extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/SessionObject.jsp

Example 13: Creating and Modifying Cookies

1| Example 13: Creating and Modifying Cookies (at-m42/Examples/lecture13/web/Cookies.jsp)
extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/Cookies.jsp

Lecture Contents

Templates Not Code!


Notes

Far from ideal models:

Groovy Server Pages

Another example

1|Example 14: Controller of HighLow game (at-m42/Examples/lecture13/web/HighLow.groovy)
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)

1|Example 14: view for HighLow game (at-m42/Examples/lecture13/web/HighLow.groovy)
// ...
 
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

1
<servlet>
    <servlet-name>Groovy Server Pages</servlet>
    <servlet-class>groovy.template.TemplateServlet</servlet-class>
</servlet>
 
<servlet-mapping>
    <servlet-name>Groovy Server Pages</servlet-name>
    <url-pattern>*.gsp</url-pattern>
</servlet-mapping>

A GSP View Page

l|Example 15(a): View for High-Low Game (at-m42/Examples/lecture13/web/HighLow.gsp)
extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/HighLow.gsp

The Controller: Dispatches to View

l|Example 15(b): Controller which dispatches to view (at-m42/Examples/lecture13/web/HighLow2.groovy)
extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/HighLow2.groovy

Other Examples of Template View implementations

Lecture Contents

Architectural Issues: Patterns

Web Tier as “Model View Controller”

Model-View-Controller pattern

MVC Patterns in the Web Tier (1)

Page Controlleran object that handles a request for a specific page or action on a web site.

Page controller

MVC Patterns in the Web Tier (2)

Front Controllerhandles all requests for a web site.

Front controller (class diagram) Front controller (activity diagram)

Component Model

Pattern is based on “components” and events Component model

Patterns in the Web Tier

MVC Frameworks

Some Example Frameworks

Front Controller:

Component model:

Many more listed here.

Lecture Summary


Home | Previous Lecture | Lectures | Next Lecture

1)
Mobile may well become more important, certainly in terms of installed systems, if not in terms of monetary value, we shall see
2)
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.
3)
This might be a long time!
4)
See Fowler Patterns of Enterprise Application Architecture Template View