简体   繁体   English

如何在调用servlet /页面加载后立即执行方法/事件

[英]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. 我有一个从另一个页面上的链接调用的servlet。 The link actually references the servlet which then SHOULD write xml to the screen (outputting RSS XML information). 该链接实际上引用了servlet,然后该servlet应该将xml写入屏幕(输出RSS XML信息)。 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. 现在,链接正确地引用并加载了servlet,但是因为我在doPost方法中具有代码,而实际上没有调用doPost方法,所以什么也没有发生。 (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? (我是Java EE的新手)那么,如何在不具有通过“ action = ..”标记引用servlet的形式的情况下执行该代码?

Can I call an init or main method that always executes on page refresh/load? 我可以调用总是在页面刷新/加载时执行的init或main方法吗?

You can implement that logic in your doGet method. 您可以在doGet方法中实现该逻辑。 It has the same method signature as your doPost method. 它具有与doPost方法相同的方法签名。

Please see this thread 请看这个主题

doGet and doPost in Servlets Servlet中的doGet和doPost

For the difference between get vs post please see this article. 有关获取与发布之间的区别,请参阅本文。

http://stevenclark.com.au/2008/01/12/get-vs-post-for-the-beginner/ 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. 您还可以重写Servlet.service方法,该方法是服务请求的入口点。 This way you will handle both POST and GET requests. 这样,您将同时处理POST和GET请求。

Alternatively, you can implement logic in doGet method and invoke doGet from doPost: 另外,您可以在doGet方法中实现逻辑并从doPost调用doGet:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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