~~SLIDESHOW~~
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.
Form depends on architecture (see previous lecture)
service( )
method through which all client requests will be sent by the servlet container software,init( )
and destroy( )
, which are called only when the servlet is loaded and unloaded (this happens rarely).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
.
javax.servlet.http.HttpServlet
and override doGet
and/or doPost
HttpServletRequest
and HttpServletResponse
parameters.HttpServletRequest
represents the request from the client.HttpServletResponse
represents the result returned by the server.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.
doGet
or doPost
: standard output is simply passed to the client!extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/helloGroovlet.groovy
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>
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.
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
<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>
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.
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.
HttpServletRequest
(Groovlet implicit variable request
) comes preloaded with all the form data, stored as key-value pairs.getParameter( )
method to look up the values. You can also get an Enumeration
(old form of Java iterator) of the field names.extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/echoForm.groovy
service( )
at the same time.service()
method must be written in a thread-safe manner.synchronized
keyword.Cookie
class. To use a cookie you simply add it to the response object. def oreo = new Cookie("AT-M42", "2009"); response.addCookie(cookie);
getCookies( )
method of the HttpServletRequest
object, which returns an list of cookie objects.def cookies = request.getCookies();
getValue()
for each cookie, to produce a String
containing the cookie contents. getValue(“AT-M42”)
will produce a String
containing “2009.”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. Session
class of the servlet API uses the Cookie
class to do its work.—-
extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/sessionPeek.groovy
static String
objects to write()
. The dynamic portions are included directly into the servlet.
<%
JSP code here %>
The leading percent sign may be followed by other characters that determine the precise type of JSP code in the tag.
extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/ShowSeconds.jsp
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 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.<%@ directive {attr="value"}* %>
<%@ page language="java" %> <%@ page session="java" import="java.util.*" %>
language
, extends
, import
, session
, buffer
, autoFlush
, isThreadSafe
, info
and errorPage
.There are three types: declarations, scriptlets and expressions.
<%! Declaration %>
: define a variable<% scriptlet %>
: fragment of java code<%= expression %>
: evaluate expression and output result
+ two types of comments: <%– jsp comment –%>
, and <!– html comment –>
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
Notes
Far from ideal models:
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 // ...
// ... 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') } } }
<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>
extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/HighLow.gsp
extern> http://www.cpjobling.org.uk/~eechris/at-m42/Examples/lecture13/web/HighLow2.groovy
<% … %>
from JSP code!Page Controller – an object that handles a request for a specific page or action on a web site.
Front Controller – handles all requests for a web site.
Front Controller:
Component model:
Many more listed here.