Hidden Form Field in Servlet

Hidden form field can likewise be utilized to store session data for a specific customer. In the event of concealed structure field a shrouded field is utilized to store customer state. For this situation client data is put away in hidden field value and recovered from another servlet.

Let's see the code to store value in hidden field.

 <:input type="hidden" name="uname" value="Mithilesh Kushwaha”>
						

Real application of hidden form field

It is broadly utilized as a part of remark type of a site. In such case, we store page id or page name in the shrouded field with the goal that every page can be exceptionally recognized

Advantage of Hidden Form Field

  • Does not need to rely on upon program whether the treat is impaired or not.
  • Inserting a straightforward HTML Input field of sort covered up is required. Thus, it's simpler to actualize.

Disadvantage of Hidden Form Field:

  • It is kept up at server side.
  • Extra structure accommodation is required on every pages.

Only textual data can be utilized.

image

index.html

<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>

FirstServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
		try{

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		String n=request.getParameter("userName");
		out.print("Welcome "+n);
		
		//creating form that have invisible textfield
		out.print("<form action='servlet2'>");
		out.print("<input type='hidden' name='uname' value='"+n+"'>");
		out.print("<input type='submit' value='go'>");
		out.print("</form>");
		out.close();

                }catch(Exception e){System.out.println(e);}
	}

}

SecondServlet.java

import java.io.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
public class SecondServlet extends HttpServlet { 
public void doGet(HttpServletRequest request, HttpServletResponse response) 
try{ 
response.setContentType("text/html"); 
PrintWriter out = response.getWriter(); 

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

out.close(); 
}catch(Exception e){System.out.println(e);} 
} 
} 

Web.xml

		<web-app>

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

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

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

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

</web-app>