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


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


Input Servlet - index.html


<html>
<head>
<title>Give the input!</title>
</head>

<center>

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

</center>
</html>

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


<web-app>

<servlet>

<servlet-name>myinputservlet</servlet-name>
<servlet-class>InputServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>myinputservlet</servlet-name>
<url-pattern>/in</url-pattern>

</servlet-mapping>

</web-app>

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


InputServlet.java


import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
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).

java.io.*: Contains PrintWriter, IOException (used here).

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

PrintWriter: Part of the java.io 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,