Name List - Fetch

Name List - Fetch

example java server servlets post fetch

This example uses the fetch function and POST requests to get the user’s name, and to show a list of every entered name.

In other words, this is a single-page web app that shows an editable list of names.

index.html contains JavaScript that uses the fetch() function to get the list of user names, and to send a new name:

<!DOCTYPE html>
      async function fetchNames() {
        const response = await fetch('/post-name-list-fetch/names');
        const nameListHtml = await response.text();
        document.getElementById('name-list').innerHTML = nameListHtml;

      async function postName() {
        const params = new URLSearchParams();
        params.append('name', document.getElementById('name').value);

        const fetchSettings = {method: 'POST', body: params};
        const response =
            await fetch('/post-name-list-fetch/names', fetchSettings);

  <body onload="fetchNames();">
    <h1>What's your name?</h1>

    <input type="text" id="name" value="Ada">
    <button onclick="postName();">Submit</button>


    <h1>Name List</h1>
    <div id="name-list">Loading...</div>
</html> handles the GET request by returning an HTML list of names, and it handles the POST request adding a new name to the list.

package io.happycoding.servlets;

import java.util.ArrayList;
import java.util.List;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class NamesServlet extends HttpServlet {

  List<String> names = new ArrayList<>();

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

    for (String name : names) {
      response.getWriter().println("<li>" + name + "</li>");

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

    String name = request.getParameter("name");


name input and list

Post Requests Examples


Happy Coding is a community of folks just like you learning about coding.
Do you have a comment or question? Post it here!

Comments are powered by the Happy Coding forum. This page has a corresponding forum post, and replies to that post show up as comments here. Click the button above to go to the forum to post a comment!