How to retrieve servlet context at initialization stage in a war package?

402 views
Skip to first unread message

Christian MICHON

unread,
Jun 5, 2015, 9:33:14 AM6/5/15
to spar...@googlegroups.com
Hi,

I've been toying with spark 2.2 and trying to deploy a small war webapp with latest tomcat8.

I'm trying to access the servlet context and paths using getServletContext(), which can only be used if the class extends HttpServlet.

I was hoping to write something like this:

public class Main extends HttpServlet implements SparkApplication {
  public void init() {

    System.out.println(getServletContext()); // this does not work the filter will never start inside tomcat8

    get("/hello", (request, response) -> {
      return "Hello World!";
    });
  }
}

Can someone help me untangle this problem? I need this to be able to open some local files within the application, once deployed and expanded in tomcat8/webapps.

Thanks in advance.
Christian

Salai Sivamal

unread,
Jun 5, 2015, 12:37:52 PM6/5/15
to spar...@googlegroups.com
1. request.session().raw().getServletContext()
or
2. Have a implement ContextListner to get the ServletContextEvent, from they you can get ServletContext
or
3. I just could not remember now, saw some code, get the ServletContext through Reflection.

I have not tried these, just my thoughts....

-Salai

Christian MICHON

unread,
Jun 5, 2015, 1:50:06 PM6/5/15
to spar...@googlegroups.com
I did nb 1 but it needs a request.
Nb 2 looks very promising.

Thanks

Christian MICHON

unread,
Jun 5, 2015, 5:16:29 PM6/5/15
to spar...@googlegroups.com
solution 2 was the perfect fit for my needs. Thanks Salai!
Reply all
Reply to author
Forward
0 new messages