Name List

Name List

September 11, 2021

example java server servlets post

This example uses an HTML form to create a POST request containing the user’s name, and then shows a list of all of the entered names.

index.html contains an HTML form:

<!DOCTYPE html>
    <title>Name Form</title>
    <h1>What's your name?</h1>

    <form action="/post-name-list/names" method="POST">
      <input type="text" name="name" value="Ada">
      <input type="submit" value="Submit">


    <p>Click <a href="/post-name-list/names">here</a> to see everybody's name.</p>
</html> handles the POST request by outputting the user’s name to the response. You can also navigate to /names to see a list of all of the entered names.

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>");

        "Click <a href=\"/post-name-list/index.html\">here</a> to enter another name.");

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

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


    response.getWriter().println("<h1>Hello " + name + "!</h1>");
        "Click <a href=\"/post-name-list/names\">here</a> to see everybody's name.");

name form

hello Ada

name 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!