Randnum
Randnum

Reputation: 1360

How to execute a method/event as soon as a servlet is called/page is loaded

I have a servlet that is called from a link on another page. The link actually references the servlet which then SHOULD write xml to the screen (outputting RSS XML information). Right now the link properly references and loads the servlet but because I have the code in the doPost method with nothing actually calling the doPost method nothing happens. (I'm new to Java EE) So how do I make that code execute without actually have a form that references the servlet through the "action =.." tag?

Can I call an init or main method that always executes on page refresh/load?

Upvotes: 1

Views: 1821

Answers (2)

Igor Nikolaev
Igor Nikolaev

Reputation: 4697

You can also override Servlet.service method which is entry point for serving requests. This way you will handle both POST and GET requests.

Alternatively, you can implement logic in doGet method and invoke doGet from doPost:

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    // do request processing
}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  
{
    doGet(request, response);
}

Upvotes: 1

r0ast3d
r0ast3d

Reputation: 2637

You can implement that logic in your doGet method. It has the same method signature as your doPost method.

Please see this thread

doGet and doPost in Servlets

For the difference between get vs post please see this article.

http://stevenclark.com.au/2008/01/12/get-vs-post-for-the-beginner/

Upvotes: 2

Related Questions