简体   繁体   中英

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?

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/

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM