Creating a Servlet
27 Sep 2016Servlets are java applications that are run on the server, responding to different requests made by clients. They most commonly are setup to respond to web-based requests although they are not limited to this scope.
From the tutorial:
A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes.
The
javax.servlet
andjavax.servlet.http
packages provide interfaces and classes for writing servlets. All servlets must implement the Servlet interface, which defines lifecycle methods. When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. TheHttpServlet
class provides methods, such asdoGet
anddoPost
, for handling HTTP-specific services.
In today’s post, I’ll walkthrough the creation of a servlet.
Setup
First up, we’re going to use Maven to generate the project infrastructure required to support our servlet.
This will generate our hello
project for us, and will create a directory structure that looks like this:
Get started
We can package our application and test it out pretty quickly:
After processing, the package
instruction will leave our project directly looking like this:
The hello.war
file can now be deployed to our application server of choice for testing. In my example here, I’m using Jetty inside of a docker container.
Navigate to http://localhost:8080/hello/, and you’ll see your jsp running.