Groovy and Tomcat, Pt5 – Bringing it together

For the final part in this miniseries I’ll create a small web application which brings together everything discussed so far. We’ll be using a Java Servlet, a Groovy Servlet and Groovyscripts to bring you the ultimate mix of all things Groovy that aren’t GRails.

What does it do?
It counts the visits you make and adds them to either the javacounter or the groovycounter. There is also a small groovyscript resetting the counter.

Web.xml

<servlet>
 <servlet-name>JavaCount</servlet-name>
 <servlet-class>net.mymilkedeek.groovytomcat.project.JavaCounter</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>JavaCount</servlet-name>
 <url-pattern>/javacount</url-pattern>
 </servlet-mapping>
 <servlet>
 <servlet-name>GroovyCount</servlet-name>
 <servlet-class>net.mymilkedeek.groovytomcat.project.GroovyCounter</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>GroovyCount</servlet-name>
 <url-pattern>/groovycount</url-pattern>
 </servlet-mapping>

counter.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
 <title></title>
</head>
<body>
 <p>Calls made:</p>
 <table>
 <tr>
 <td>Java</td>
 <td><c:out value="${javacounter}" /></td>
 </tr>
 <tr>
 <td>Groovy</td>
 <td><c:out value="${groovycounter}" /></td>
 </tr>
 </table>
</body>
</html>

reset.groovy

request.session.setAttribute("javacounter", 0)
request.session.setAttribute("groovycounter", 0)

response.sendRedirect("counter.jsp")

Java Servlet

public class JavaCounter extends HttpServlet {

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 Object countObject = req.getSession().getAttribute("javacounter");

 int count = 0;

 if ( countObject != null ) {
 count = (Integer) countObject;
 }

 req.getSession().setAttribute("javacounter", count+1);

 resp.sendRedirect("counter.jsp");

Groovy Servlet

class GroovyCounter extends HttpServlet {

 @Override
 protected void doGet (HttpServletRequest req, HttpServletResponse resp) {
 def countObject = req.session.getAttribute("groovycounter")

 def count = 0

 if ( countObject != null ) {
 count = (Integer) countObject
 }

 req.session.setAttribute("groovycounter", count+1)

 resp.sendRedirect("counter.jsp")
 }
}

And that’s the end of this series. The code can be checked out at:¬†https://bitbucket.org/mymilkedeek/tutorials/src