Anna University Regional Campus, Coimbatore

Department of Computer Science and Engineering

Experiment 5A - Invoking Servlet from HTML Forms



AIM:

To write an HTML program for invoking a servlet using HTML forms.

ALGORITHM:

  1. Start by creating an HTML form with necessary fields like Name, Email, Phone, and Country.
  2. Define the form with a POST method and set the action to the servlet path.
  3. In the servlet, use request parameters to retrieve data submitted by the form.
  4. Process the data and send a response back to the user displaying the submitted information.
  5. Compile and run the servlet on a web server like Tomcat.
  6. Test the servlet by submitting the form and verifying the response.

PROGRAM:

HTML Form (index.jsp)

<!DOCTYPE html>
<html>
<head>
    <title>Student Information Form</title>
</head>
<body>
    <h1 style="text-align: center; color: red;">Student Registration</h1>
    <form action="StudentServlet" method="post" style="text-align: center;">
        <label>Name:</label>
        <input type="text" name="name" required><br><br>
        <label>Email:</label>
        <input type="email" name="email" required><br><br>
        <label>Phone:</label>
        <input type="tel" name="phone" required><br><br>
        <label>Country:</label>
        <select name="country" required>
            <option value="" disabled selected>Select your country</option>
            <option>USA</option>
            <option>UK</option>
            <option>India</option>
            <option>Australia</option>
        </select><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>
            

Servlet Code (Servlet.java)

package servlet;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import java.io.*;

@WebServlet("/StudentServlet")
public class Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        String country = request.getParameter("country");

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html><body><center>");
        out.println("<h1 style='color: green;'>Welcome, " + name + "!</h1>");
        out.println("<p>Email: " + email + "</p>");
        out.println("<p>Phone: " + phone + "</p>");
        out.println("<p>Country: " + country + "</p>");
        out.println("</center></body></html>");
    }
}
            

Sample Output:

Output Image 1 Output Image 2

RESULT:

Thus, the invocation of a servlet from HTML form has been developed and tested successfully.