Showing posts with label Java Web Development. Show all posts
Showing posts with label Java Web Development. Show all posts

Friday, September 4, 2026

Java: Sending Data from JSP to Servlet

Sending Data from Jsp to Servlet or Communication between Jsp & Servlet , we need certain things like
  • A JSP File
  •  Deployment Descriptor (web.xml)
  • A Servlet File (Normal Java File)

Jsp File (index.jsp)
<form action="test1" method="get">
    <label>Name:</label>
    <input type="text" name="txtname">
    <input type="submit" value="Submit">
</form>




Servlet File (test1.java)

Note: In this example, the form uses the GET method, so the Servlet handles the request in doGet(). If the form uses POST, the Servlet should generally handle it in doPost(). The service() method is responsible for dispatching HTTP requests to methods such as doGet() and doPost(), so application code normally overrides doGet() or doPost() rather than overriding service() directly.

import java.io.IOException;
import java.io.PrintWriter;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/test1")
public class Test1 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");

        String name = request.getParameter("txtname");

        PrintWriter out = response.getWriter();
        out.println("<h2>Hi, I am " + name + "</h2>");
    }
}

Alternative: Using web.xml

Instead of using @WebServlet, the Servlet can be mapped using the web.xml deployment descriptor. This approach is common in older Java EE applications and is still supported.

<servlet> <servlet-name>test1</servlet-name> <servlet-class>Test1</servlet-class> </servlet> <servlet-mapping> <servlet-name>test1</servlet-name> <url-pattern>/test1</url-pattern> </servlet-mapping>

The url-pattern defines the URL path used to access the Servlet. In this example, the JSP form uses action="test1", which corresponds to the /test1 Servlet mapping.



Note: In web.xml url-pattern is the path for browser ,so any name can be used (not /test1). we need & tag for run & map a servlet to the path. But, Url-pattern must match with the form action .

Legacy Java EE note: If you are working with an older application running on Tomcat 9 or earlier, you may see imports such as javax.servlet.http.HttpServlet. Tomcat 10 and later use jakarta.servlet.http.HttpServlet, so applications may require migration when moving from Tomcat 9 to Tomcat 10+