How can values be passed from a servlet to a JSP page?
A Servlet can pass values to a JSP page through either request forwarding or request redirection.
- Request forwarding: In Servlet, data can be passed to a JSP page by setting attributes in the request object. Code example:
request.setAttribute("message", "Hello JSP!");
RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
dispatcher.forward(request, response);
In a JSP page, the value passed can be accessed through the EL expression ${message}.
- Request forwarding: In Servlet, data can be passed to a JSP page by setting URL parameters or storing data in the Session. Example code:
response.sendRedirect("index.jsp?message=Hello JSP!");
In JSP pages, you can retrieve the value passed in the URL parameters by using request.getParameter(“message”), or get the value saved in the Session by using ${sessionScope.message}.
It should be noted that request forwarding is an internal redirection by the server, while request redirection is a redirection by the client.