Saturday, June 20, 2020

Creating a Java Web App Servlet in Visual Studio Code

Would you like to add a Java Http Servlet to your Java web app project? This guide will cover doing just that. 

Rewind - Create a Java Project First
If you missed the Create a Java Project in VS Code, check it out first. 

3 Steps
It takes three easy steps to wire up an HttpServlet.
  1. Adding the HttpServlet dependency
  2. Add a Java HttpServlet class
  3. Map an endpoint to the HttpServlet class.

Add the Dependency to your Project
In a Maven project add the dependency below. In a Java standard project, download the jar and add it to the build path. Check the latest version out here.
Add the Http Servlet Class 
Create an HttpServlet and add it to your source path. This example only shows how to handle a get request. You can handle other request methods too, such as: doDelete, doHead, doOptions, doPost, doPut, and doTrace.

package com.brandondonnelson;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ApiServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

      PrintWriter out = response.getWriter();
      out.println("./api works. Try ./api/getMessage");


Add the Http Servlet Endpoint to the web.xml
A servlet can be configured in more than one way. In this way, it must be stated in the web.xml server instructions and mapped to an endpoint, like ./api. If you notice, the ./api endpoint is bound to the ApiServlet, so when the path is dialed up http://something.tld/api, it will run the servlet doGet path. 

<web-app xmlns=""

  <display-name>My App</display-name>


Load the HttpServlet
Now that everything is configured. Load the page. 
  • Open the servlet by going to: http://domain.tld/api

Video Tutorial
See the debugging a servlet in action in this video.

1 comment:

Shubham Rajput said...

Thanks a lot. you know what you hv given the best explanation

Trying out the Dart Analysis Server

I wanted to see how the Dart Analysis Server was put together and worked. I started looking to see how I could wire it up and try out the co...