Showing posts with label Hidden Form Field. Show all posts
Showing posts with label Hidden Form Field. Show all posts

Friday, 24 April 2015

Servlets : Hidden form field Demo

🚀 Master Java Servlets & Web Development!

Subscribe to Ram N Java for clean, beginner-friendly coding tutorials and web development guides!

👉 Click Here to Subscribe Now

What is Session Tracking using Hidden Form Fields?

The HTTP protocol is stateless, meaning each request sent by a browser is treated as completely independent by the web server. To maintain user state across multiple pages, Java Servlets provide several session tracking techniques. One of the simplest and most effective approaches is using Hidden Form Fields (<input type="hidden">).

Hidden form fields let you embed invisible information inside an HTML form. When the user submits the form, the hidden parameter is sent along with visible fields to the next servlet, allowing continuous state tracking without relying on browser cookies.

Step 1: Create the First HTML Form (index.html)

The user begins by entering initial information (such as their username) in a standard form that submits to the first servlet:

<form action="FirstServlet" method="post">
  Enter your Name: <input type="text" name="userName" /><br><br>
  <input type="submit" value="Continue" />
</form>

Step 2: Embed Hidden Field in First Servlet (FirstServlet.java)

The first servlet retrieves the submitted name and dynamically builds a second HTML form containing a hidden field with the user's data:

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

PrintWriter out = response.getWriter();
out.println("<h2>Welcome " + userName + "</h2>");
out.println("<form action='SecondServlet' method='post'>");
out.println("<input type='hidden' name='uname' value='" + userName + "'/>");
out.println("Enter Email: <input type='text' name='email'/><br><br>");
out.println("<input type='submit' value='Submit Details'/>");
out.println("</form>");

Step 3: Retrieve Hidden Values in Second Servlet (SecondServlet.java)

When the second form is submitted, the second servlet extracts both the visible form field and the hidden field using standard request parameter methods:

String userName = request.getParameter("uname");
String email = request.getParameter("email");

PrintWriter out = response.getWriter();
out.println("<h3>Submission Received Successfully!</h3>");
out.println("<p>Username: " + userName + "</p>");
out.println("<p>Email: " + email + "</p>");

Advantages & Limitations of Hidden Form Fields

  • Advantage: Always works even if the user disables cookies in their browser.
  • Advantage: Lightweight and does not consume server-side session memory.
  • Limitation: Only works with form submissions (POST/GET via form tags); cannot track state through standard hyperlink navigation.
  • Limitation: Data is visible in the page source, so sensitive credentials should never be stored in plain text.

📺 Related Session Tracking Tutorials

Learn more about session management mechanisms in Java Servlets from our channel:


Click here to watch in Youtube : https://www.youtube.com/watch?v=64hZwZ8hDs0&list=UUhwKlOVR041tngjerWxVccw&index=4

Click the below Image to Enlarge
Servlets : Hidden form field Demo
Servlets : Hidden form field Demo
Servlets : Hidden form field Demo
Servlets : Hidden form field Demo
Servlets : Hidden form field Demo
Servlets : Hidden form field Demo

FirstServlet.java
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FirstServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;

    public void init() throws ServletException
    {
        System.out.println("-----------------------------------------");
        System.out.println(" Init method is called in "
                + this.getClass().getName());
        System.out.println("--------------------------------------");
    }

    public void doGet( HttpServletRequest request, HttpServletResponse response )
            throws ServletException, IOException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        String userName = request.getParameter("userName");
        out.print("Welcome " + userName);

        // creating form that have invisible textfield
        out.print("<form action='servlet2'>");
        out.print("<input type='hidden' name='userName' value='" + userName
                + "'>");
        out.print("<input type='submit' value='go'>");
        out.print("</form>");
        out.close();
    }

    public void destroy()
    {
        System.out.println("-----------------------------------------");
        System.out.println(" destroy method is called in "
                + this.getClass().getName());
        System.out.println("-----------------------------------------");
    }

}
SecondServlet.java
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SecondServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;

    public void init() throws ServletException
    {
        System.out.println("-----------------------------------------");
        System.out.println(" Init method is called in "
                + this.getClass().getName());
        System.out.println("--------------------------------------");
    }

    public void doGet( HttpServletRequest request, HttpServletResponse response )
            throws ServletException, IOException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        // Getting the value from the hidden field
        String userName = request.getParameter("userName");
        out.print("Hello " + userName);

    }

    public void destroy()
    {
        System.out.println("-----------------------------------------");
        System.out.println(" destroy method is called in "
                + this.getClass().getName());
        System.out.println("-----------------------------------------");
    }

}
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    metadata-complete="true" version="3.0">
    <display-name>HiddenFormFieldDemo</display-name>
    <description>
        This is a simple web application with a source code organization
        based on the recommendations of the Application Developer's Guide.
    </description>

    <servlet>
        <servlet-name>s1</servlet-name>
        <servlet-class>FirstServlet</servlet-class>
    </servlet>

    <servlet>
        <servlet-name>s2</servlet-name>
        <servlet-class>SecondServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>s1</servlet-name>
        <url-pattern>/servlet1</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>s2</servlet-name>
        <url-pattern>/servlet2</url-pattern>
    </servlet-mapping>

</web-app>
index.html
<html>
<body>
    <form action="servlet1">
        Name:<input type="text" name="userName" /><br /> 
        <input type="submit" value="go" />
    </form>
</body>
</html>

Environment Used

JDK version :1.7.0_51
Tomcat version : 7.0.50

To Download HiddenFormFieldDemoApp Project Click the below link

https://sites.google.com/site/javaee4321/jdbc/HiddenFormFieldDemoApp.zip?attredirects=0&d=1

See also:

  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • Saturday, 28 June 2014

    Servlets : Hidden Form Field

    🚀 Master Java & Servlets with Ram N Java!

    Subscribe to get clear, beginner-friendly tutorials right when they drop.

    🔔 Subscribe to Ram N Java

    What is a Hidden Form Field?

    Because HTTP is a stateless protocol, web applications need reliable mechanisms to retain context between client requests. One of the classic techniques used in Java web development is the Hidden Form Field.

    A hidden form field is an invisible HTML form input element that stores client-specific information directly within the webpage. When the user submits the form, the data stored in this hidden field is automatically posted back to the server alongside visible inputs.

    How Hidden Form Fields Work

    Hidden fields are declared using the standard HTML <input> tag with the type attribute set to "hidden":

    <input type="hidden" name="userId" value="1001" />

    When the form containing this tag is submitted, the target servlet retrieves the stored value using standard parameter handling:

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

    Advantages and Limitations

    Advantages:

    • Browser Independence: Operates seamlessly regardless of whether cookies are enabled, disabled, or blocked in the browser.
    • Lightweight: Requires no server memory or session store footprint, as state is maintained entirely in the HTML payload.

    Limitations:

    • Form Bound: State is only passed when submitting an HTML form; simple anchor hyperlinks cannot pass hidden field data.
    • Security Concerns: The field is hidden from view on the screen, but its value remains fully inspectable and editable via the browser's "View Page Source" or developer tools.

    Recommended Next Watch

    Explore more session tracking and state management techniques in Java Servlets:


    Click here to watch in Youtube : https://www.youtube.com/watch?v=nbLc7e7EJiI

    Click the below Image to Enlarge

    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • Tutorials