0

Goal: I have only one page and when page loads, it should run the query from servlet and display all values on index.jsp page.

Existing problem: when i am submitting the page from "Submit" button to another page, it works fine but when i load page index.jsp with values, its gives NullPointerException because servlet didn't run before the index.jsp page.

My Servelet:

public class GetStudentController extends HttpServlet {
    private static final long serialVersionUID = 1L;

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


        StudentDao sd = new StudentDao();  // model
        StudentInfo si = sd.getInfo();

        request.setAttribute("si", si);

        RequestDispatcher rd = request.getRequestDispatcher("display.jsp");
        rd.forward(request, response);
}
}

my JSP:

<body>
<form action="displayStud">         <--my servlet controller name -->
Student id <input type="text" name = "sid">
<button name="test" type="submit"">Primary Button</button>
</body>
</html>

<button type="submit" class="btn btn-primary" name="action" formaction="ddd" value="find">Test2</button>
    <!-- <input type ="submit" value ="Submit"> -->
</form>

StudentDao has query in there

Again: I just want it to run the same code on page load and all data should load(without click on submit)

Thanks for the help

Eddie
  • 45
  • 2
  • 10
  • so when you hit submit button the page were the navigator goes renders the jsp with the proper data (i don't see how you are accesing the "si" attribute in the jsp) , and when you do "page load",,, what is page load? a refresh? does this link helps https://stackoverflow.com/questions/10898393/how-to-access-a-request-attribute-set-by-a-servlet-in-jsp? – Victor May 05 '20 at 14:19

1 Answers1

0

You can use the value set in the request scope using jstl or expression language.

request.setAttribute("si", si);

Something like:

Student id <input type="text" name = "sid" value="${requestScope.si.id}">
  • Problem is not setting the value, problem is run the servlet before loading the .jsp page – Eddie May 04 '20 at 21:13
  • You should call the servlet uri then first.You should map it in web.xml https://docs.oracle.com/cd/E13222_01/wls/docs92/webapp/configureservlet.html – Dharmendra Vishwakarma May 04 '20 at 22:59
  • My servlet tag is already in xml, but still giving null pointer ex. – Eddie May 05 '20 at 17:23
  • I believe you didn't forget to add the required jar. Please go through https://www.tutorialspoint.com/jsp/jsp_standard_tag_library.htm and check what might be missing. Also just to give you an overview, your servlet is mapped in web.xml with URL pattern and when you hit a URL in the browser, it makes a GET request which will call this doGet method on the servlet. This method will forward the request to JSP with data and it will render the output in the response. Make sure to add jar for jstl core. – Dharmendra Vishwakarma May 05 '20 at 19:59