I want to delivered the URL of a servlet (MyServlet.java) to a java class (Test.java). Test.java is located in a Project.jar in folder lib of WEB-INF. So I have tried to pass the Servlet URL to Test.java
import projct.Test;
public class MyServlet extends HttpServlet {
@Override
public void init() throws ServletException {..}
@Override
public void destroy() {..}
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
new Test().setServleturl(request.getRequestURL().toString());
request.getRequestDispatcher("/index.html").forward(request, response);
}
}
The Test.java class looks like this:
public class Test {
private static String var;
public static String getVar() {
return var;
}
public static void setVar(String var) {
Test.var = var;
}
}
After Diployment is the value of var still null.
What am I doing wrong?
And how can you write the URL from MyServlet.java in var from Test.java?
I assume that
setServleturl()is in factsetVar(), because it wouldn’t compile.Of course it’s null after deployment.
processRequest()is only called when a request… is processed. Make an HTTP request to your servlet, and the code will be executed.That said, what you have there seems like a really bad idea, and it’s not thread-safe (
setVar()andgetVar()should be synchronized). Moreover, these methods should be called usingTest.setVar(), and notnew Test().setVar(), since they’re static methods. What are you trying to achieve?EDIT: it seems the problem is to read files from WEB-INF at deployment time. To do that, use a ServletContextListener, and in its
contextInitialized()method, get the servlet context from the event, and callservletContext.getResourceAsStream("/WEB-INF/theFileToLoad").