Even or Odd

A Java Web-Service

This is a quick demo, showing how to create a Java web-service in just a few minutes. I'm assuming you have Java and Tomcat already installed on you computer and use IntelliJ as your IDE, and gradle as your build-automation system.

The simple task is to create a web-service that can answer if a provided number is even or odd. So for example, you would type "http://localhost:8080/eo/evenORodd?x=3" into the URL address input field of your browser, and then see something like this as the result: **3 is odd **

Not all that sophisticated, I know that, but that's not the point.

WebService

Start a project using the Jarkata EE project settings shown below.

  • Name: 'webservice'
  • Template: 'Library'
  • App Server: 'Tomcat 10...'
  • Language: Java
  • Build System 'Gradle'
  • Group:
  • JDK '21'
  • Version: 'Jakarta EE 10'
  • Dependencies: 'Servlet (6.0.0)'

Gradle

Idea's project wizard creates a builds.gradle file that look pretty good already, but needs a few touches (note the lines with '// *') Most importantly, test and logging dependencies need to be added.

plugins {
    id 'java'
    id 'war'  // *
}

group 'edu.erau.coe'
version '1.0-SNAPSHOT'
war.archiveFileName = 'eo.war'  // *

repositories {
    mavenCentral()
}

ext {
    junitVersion = '5.10.0'
}

sourceCompatibility = '11'
targetCompatibility = '11'

tasks.withType(JavaCompile) {
    options.encoding = 'UTF-8'
}

dependencies {
    compileOnly('jakarta.servlet:jakarta.servlet-api:6.0.0')
    //  Logger
    implementation 'org.apache.logging.log4j:log4j-api:2.23.1'  // *
    implementation 'org.apache.logging.log4j:log4j-core:2.23.1' // *
    // Tests
    testImplementation('jakarta.servlet:jakarta.servlet-api:6.0.0')  // *
    testImplementation('org.easymock:easymock:5.2.0')                // *
    testImplementation("org.junit.jupiter:junit-jupiter-api:${junitVersion}")
    testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:${junitVersion}")
}

test {
    useJUnitPlatform()
}

Java

Finally, here is the Java code implementing the web service. The Here is the Java code that implements the service, using the @WebServlet annotation:

package edu.erau.coe;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;


/**
 * WebService, answering the question, if the given integer x is even or odd.
 * Remember: requestURI = contextPath + servletPath + pathInfo
 * - contextPath is basically the name of the WAR when it's deployed
 * - servletPath is declared as "/evenORodd" below.
 */
@WebServlet(value = "/evenORodd", name = "EO")
public class WebService extends HttpServlet {
    private final Logger logger = LogManager.getLogger(WebService.class);

    @Override
    protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) {
        try {
            final int x = Integer.parseInt(req.getParameter("x"));
            resp.setHeader("Content-Type", "text/html; charset=UTF-8");
            resp.getWriter().printf("%d is %s", x, (x % 2) == 0 ? "even" : "odd");
            resp.setStatus(HttpServletResponse.SC_OK);
            logger.info("That went well.");
        } catch (Exception ex) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            logger.error(ex.toString());
        }
    }
}

Java Test Code

Let's also show how this implementation can be tested, even without lauching the server. EasyMock allows for elegant unit testing.

package edu.erau.coe;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.Test;

import java.io.PrintWriter;
import java.io.StringWriter;

import static org.easymock.EasyMock.*;
import static org.easymock.EasyMock.verify;


class WebServiceTest {

    @Test
    void doGet() throws Exception {
        PrintWriter pw = new PrintWriter(new StringWriter());
        pw.print("3 is odd");

        HttpServletRequest req = niceMock(HttpServletRequest.class);
        expect(req.getParameter("x")).andReturn("3");

        HttpServletResponse res = niceMock(HttpServletResponse.class);
        expect(res.getWriter()).andReturn(pw);

        replay(req, res);
        new WebService().doGet(req, res);
        verify(req, res);
    }
}

Logging

Logging is important once things start to fail .. let's prepare for that too. Putting this log4j2.xml document into the project's resource folder will allow for some minimal logging functionality.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<Appenders>
    <Console name="stdout" target="SYSTEM_OUT">
        <PatternLayout pattern="[%d{HH:mm:ss.SSS}][%t][%-5level][%logger{36}] %msg%n"/>
    </Console>
</Appenders>
<Loggers>
    <Root level="INFO">
        <AppenderRef ref="stdout" level="INFO"/>
    </Root>
</Loggers>
</Configuration>

At this point the IntelliJ Project looks something like this. We have added a java source and a java test file, a log4J2 descriptor and edited the build.gradle file.

To see the web-service working (e.g. debugging it) and launching it from within IntelliJ, we need to add a Run/Debug configuration. Select "Tomcat Server" and "Local" once you have found it. Initially, you will have to tell IntelliJ where Tomcat is installed on you Computer ..

E.g.: set the url to: http://localhost:8080/eo/

Do not step over the next step: Open the Deployment tab and change the Application context to "/eo"

Now it's time to run the Tomcat configuration you just created .. hopefully resulting in something like this:

Make sure you added your query "/evenORodd?x=3" to the url, e.g: http://localhost:8080/eo/evenORodd?x=3

Find the code for this kiss (keep it simple stupid) project here: https://github.com/wolfpaulus/even-or-odd