Examples / Server Examples / Name Input

Name Input

example java server servlets post

This example uses an HTML form to create a POST request containing the user’s name.

index.html contains an HTML form:

<!DOCTYPE html>
    <title>Name Form</title>
    <h1>What's your name?</h1>
    <form action="/post-name/hello" method="POST">
      <input type="text" name="name" value="Ada">
      <input type="submit" value="Submit">

GreetingServlet.java handles the POST request by outputting the user’s name to the response:

package io.happycoding.servlets;

import java.io.IOException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class GreetingServlet extends HttpServlet {

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

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

    response.getWriter().println("<h1>Hello " + name + "!</h1>");

name form

hello Ada

Comments and Questions

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