Java Reference
In-Depth Information
void testDoGetWithNoName() {
MockHttpServletRequest request = new MockHttpServletRequest()
MockHttpServletResponse response = new MockHttpServletResponse()
MockHttpSession session = new MockHttpSession()
request.session = session
servlet.doGet(request, response)
assert 'hello.jsp' == response.forwardedUrl
assert request.getAttribute("name") == 'Hello, World'
assert session.getAttribute("count") == 1
}
@Test
void testDoGetWithName() {
MockHttpServletRequest request = new MockHttpServletRequest()
MockHttpServletResponse response = new MockHttpServletResponse()
MockHttpSession session = new MockHttpSession()
request.session = session
request.setParameter('name','Dolly')
servlet.doGet(request, response)
assert 'hello.jsp' == response.forwardedUrl
assert request.getAttribute("name") == 'Hello, Dolly'
assert session.getAttribute("count") == 1
}
}
The ServletCategory isn't needed in the tests, because I'm already using mock ob-
jects rather than the Servlet API classes. Note that the tests check both the request
and session attributes and the forwarded URL from the doGet method. The Ser-
vlet-Category class is a simple example of how to use Groovy's metaprogramming
capabilities to simplify an API.
As a simple alternative to normal servlet development, Groovy provides groovlets.
10.2. Easy server-side development with groovlets
Groovlets are groovy scripts that are executed in response to HTTP requests. A built-in lib-
rary class called groovy.servlet.GroovyServlet executes them. Like all Groovy
scripts, they're associated with a binding that holds many pre-instantiated variables.
To use a groovlet, first configure the GroovyServlet to receive mapped requests. A
typical way of doing so is to add the following XML to the standard web application de-
ployment descriptor, web.xml:
Search WWH ::




Custom Search