Servlet HTML

 

 

Interacting with HTML forms using Java Servlets

 

 

ServletsHome


For any website to receive data from user generally forms are used. These forms built using HTML language. You should have a basic HTML knowledge. If not yet have an idea on HTML, Please learn the Basics of HTML and proceed with this tutorial. 

In this tutorial, you learn how to read data from forms and print it using servlets.

Form contains different type of controls. Such as text boxes, checkboxes, radio buttons, combo boxes, textarea and so on. We learn how to use these control with different examples.

 
Example1: 

 

This example having a form with input control - textbox and submit button.

 
 
hello.html 
 
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  </head>
  <body>
   <form name="form1" method="post" action="GenServletHtmlName">
    Enter Your Name:<input type=textbox name="t1" value="">
    <input type=submit name="sub" value="Go">
   </form>
  </body>
</html>
 
 

A servlet program below will read the submitted name in the form.  

 
HelloServlet.java 
 
 
 
package czon;

 

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

 public class HelloServlet extends GenericServlet{

 public void service(ServletRequest req,ServletResponse res)
	throws ServletException,IOException{
  PrintWriter out= res.getWriter();
  String sname= req.getParameter("t1");

  out.println("Hello..."+sname);
  out.close();
}
}
  
 
Example2:
 
 
 
 
Add.html 
 
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<body bgcolor="orange"> 
 
<form  name="f1" method="post" action="AddDemo.java">
    Enter FirstNo: <input type=textbox name="t1" value=""><br>
    Enter SecondNo:<input type=textbox name="t2" value=""><br>
<input type=submit name="sub" ><br> 
</form>
 
</body>
</html>

 

 
package czon;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.*;


public class AddDemo extends HttpServlet {

 public void doGet(HttpServletRequest req,HttpServletResponse res)
	throws ServletException,IOException{
 
  PrintWriter out= res.getWriter(); 
 
  String s1= req.getParameter("t1");
  String s2= req.getParameter("t2"); 
 
 int c=Integer.parseInt(s1)+Integer.parseInt(s2);

 out.println("c="+c);
 out.close();
}
}

 

 Java Tutorial Home

Comments

Popular posts from this blog

Using javascript pass form variables to iframe src

Creating a new PDF by Merging PDF documents using TCPDF

Import excel file into mysql in PHP