Input Servlet - Print User Input in Java Servlets

Input Servlet Introduction

Following steps are involved in Input Servlet.

1. User gives input.
2. Request is sent to Servlet class by servlet container when user clicks submit
3. Servlet class handles the input, gives response.

Input Servlet - Folder Structure

       |_ inputservlet
                   |_ index.html
                   |_ WEB-INF
                              |_ web.xml
                              |_ classes
                                       |_ InputServlet.class

Input Servlet - index.html

<title>Give the input!</title>


  <form action="/inputservlet/in" method="get">

     <b>Name :</b> <input type="text" name="mytext" width="20">
     <input type="submit" value="Welcome me!" name="submit">



form: User input is taken in a form containing input fields.

action="/inputservlet/in": /in is the url pattern in web.xml and the inputservlet is the name of the project (folder name). The project folder name must be specified here for sure, else the statement means to search in the webapps directory, not within the project.

method="get": Submit input through url.

name="mytext": Used to get the value in the Servlet class.

Input Servlet - web.xml









Cant understand web.xml? See Understanding web.xml in Java Servlets

import javax.servlet.http.*;
import javax.servlet.*;
public class InputServlet extends HttpServlet

public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
PrintWriter pw=res.getWriter();
String user=req.getParameter("mytext");
pw.println("<h1>Welcome "+user+"</h1>");


javax.servlet.http.*: Contains HttpServlet, HttpServletRequest, HttpServletResponseclasses (used here).

javax.servlet.*: Contains ServletException (used here).*: Contains PrintWriter, IOException (used here).

doGet(): For url type submission, submission through url, observe method="get" in index.html

PrintWriter: Part of the package.

req.getParameter("mytext"): Get the value (user input value) in the input field named mytext

pw.println("<h1>Welcome "+user+"</h1>"): Present in the PrintWriter class, write Welcome along with user within <h1> (here).

Note: Do not forget to compile the class and re/start tomcat! ;)

Posted by at on

Tags: Servlets,