Issue
I'm making a hostel management system with backend in java. I made a header class that shows the menu and I want it to be included on every servlet of my project. I have tried using request dispatcher. like this:
RequestDispatcher rd1 = req.getRequestDispatcher("/header");
rd1.include(req, res);
When I put it on some servlet, the output of that servlet is removed(only that output which is placed after this include line) and only header servlet is displayed. I have overloaded both doGet()
and doPost()
methods in header servlet.
The Following picture shows that my header is working fine
An Example servlet is here in which I'm including header servlet.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class add extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws IOException,ServletException
{
PrintWriter out = res.getWriter();
res.setContentType("text/html");
out.println("<html><head><title>Add student</title></head>");
RequestDispatcher rd1 = req.getRequestDispatcher("/header");
rd1.include(req, res); //I want to show the data after this line as well
out.println("<form method='post' action='addtoDatabase'>");
out.println("Roll Number : <input type='text' name='roll' placeholder='student Roll Number'><br>");
out.println("Name : <input type='text' name='studentName' autofocus placeholder='student name'><br>");
out.println("room number : <input type='text' name='roomNumber' placeholder='Room Number'><br>");
out.println("Address : <input type='text' name='address' placeholder='Address'><br>");
out.println("Phone : <input type='text' name='phone' placeholder='03001234567'><br>");
out.println("<input type='submit' value='Add Student'> ");
out.println("</form></body></html>");
out.close();
}
}
In the above code, the HTML form is not been displayed on the browser. Only the header is displayed as I have shown in the following screenshot.
How can I combine the output of both header and any other servlets on the browser?
Solution
there are Session Scope
, also have Application Scope
. I am wondering what are you achieving is share some data between different sessions. That is you need Application Scope
. That is ServletContext , Please refer to Using application scope variables in java
Answered By - Qingfei Yuan
Answer Checked By - Mildred Charles (JavaFixing Admin)