Name List - Fetch


Name List - Fetch


September 11, 2021

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>
<html>
  <head>
    <title>Names</title>
    <script>
      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);

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

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

    <hr>

    <h1>Name List</h1>
    <div id="name-list">Loading...</div>
  </body>
</html>

NamesServlet.java 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.io.IOException;
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;

@WebServlet("/names")
public class NamesServlet extends HttpServlet {

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

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

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

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

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

    names.add(name);
  }
}

name input and list



Post Requests Examples

Comments

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!