gpt4 book ai didi

JavaServlet : Force init to create data object on Payara server start?

转载 作者:行者123 更新时间:2023-11-30 06:09:09 27 4
gpt4 key购买 nike

我正在寻找一种在第一个请求之前在我的java servlet(在Payara上)中生成数据对象的方法,因为创建的数据对象需要一些时间来解析其他网站(大约4秒)。

我认为设置就足够了

@WebServlet(urlPatterns = "/reports/*", loadOnStartup = 1)

首先在 payara 服务器启动时强制 servlet 容器进行初始化(基于 http://www.codejava.net/java-ee/servlet/webservlet-annotation-examples )。然而,它不起作用。我的第一个请求仍然有 4 秒的延迟,后续请求没有延迟。以下代码有效,问题只是第一个请求的延迟。

@WebServlet(urlPatterns = "/reports/*", loadOnStartup = 1)
public class SingleReportServlet extends HttpServlet {

ReportData m_myData;

@Override
public void init() throws ServletException {
m_myData = new ReportData(); //This takes about 4 seconds, once
System.out.println("My servlet has been initialized");
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String requestPath = request.getPathInfo();
String[] components = requestPath.split("/");
String requestedData = components[components.length-1].trim().toUpperCase();
String report = m_myData.getFullReport(requestedData, Locale.GERMAN, DisplayType.HTML_PARTIAL);
String headline = "Report for "+requestedData;
System.out.println(headline);
System.out.println(report);
request.setAttribute("headline", headline);
request.setAttribute("report", report);
request.getRequestDispatcher("/WEB-INF/singleReport.jsp").forward(request, response);
}
}

最佳答案

我建议您使用 ServletContextListener

,而不是在 servlet init 方法中初始化 ReportData

例如

@WebListener
public class ServletContextListenerImpl implements ServletContextListener {

@Override
public void contextInitialized(ServletContextEvent sce) {
ReportData m_myData = new ReportData ();
System.out.println("My ServletContextListenerImpl has been initialized");

// then add to your session for later use
sce.getServletContext().setAttribute("RDATA", m_myData);
}
..
}

关于JavaServlet : Force init to create data object on Payara server start?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50637808/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com