2

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.

Screenshot of remove page

How can I combine the output of both header and any other servlets on the browser?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

hey, @Qinfdei I have checked the links you provided me. I was about to try addServlet() function but then I only removed the close statement from header servlet. Everything Worked fine for me then.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.