Hidden Form Field
In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the state of an user.
In such case, we store the information in the hidden field and get it from another servlet. This approach is better if we have to submit form in all the pages and we don't want to depend on the browser.
Let's see the code to store value in hidden field.
- <input type="hidden" name="uname" value="Vimal Jaiswal">
Here, uname is the hidden field name and Vimal Jaiswal is the hidden field value.
Real application of hidden form field
It is widely used in comment form of a website. In such case, we store page id or page name in the hidden field so that each page can be uniquely identified.
Advantage of Hidden Form Field
- It will always work whether cookie is disabled or not.
Disadvantage of Hidden Form Field:
- It is maintained at server side.
- Extra form submission is required on each pages.
- Only textual information can be used.
Example of using Hidden Form Field
In this example, we are storing the name of the user in a hidden textfield and getting that value from another servlet.
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);
-
-
- 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();
-
-
- 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>
No comments:
Post a Comment