JSP and Servlet Interaction in Java with an example

Below example shows how to print the data that is retrieved from a Form using a JSP and then passing it to a Servlet for printing it on the GUI.
What components are needed for this ?
  • JSP Page with a form input
  • A Controller 
  • Web Configuration file (web.xml)
JSP Page :

Below is the code for the JSP Page with a Form input. The Form has the below input fields.
  • First name
  • Last name
  • City
The JSP Page code looks like below.

Index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome Page</title>
</head>
<body>
 <form action="/Index" method="post">
        <input type="text" name="fname"/><br>        
        <input type="text" name="lname"/>
        <input type="text" name="city"/>                                                                                                                                                                         
        <input type="submit" value="submit">            
    </form>

</body>
</html>

Once we have the JSP with the Form data, we need to create the Controller. Below is the code for the controller.


ControllerServlet.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ControlServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String fname = request.getParameter("fname");
        String lname = request.getParameter("lname");
        String city = request.getParameter("city");
        System.out.println("FirstName :"+ fname);
        System.out.println("Lastname :"+ lname);
        System.out.println("City :"+ city);
    }

}
Once we have created the Controller, we need to map this in the web.xml file. Below is the code for the web.xml file for the servlet mapping.

web.xml
  <servlet>
    <servlet-name>controllerServlet</servlet-name>
    <servlet-class>com.developersareana.ControllerServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>controllerServlet</servlet-name>
    <url-pattern>/Index</url-pattern>
  </servlet-mapping> 
Hope this example helps you understand how you can pass the data from the JSP to a Servlet.

No comments:

Post a Comment

Please Provide your feedback here