比如我的访问地址是http://localhost:888/project/index
我的web工程放在tomcat的webapps的project目录下
我想获取http://localhost:888/project这个路径,主要是为了发ajax请求,请问怎么办?我想把这个地址在tomcat启动的时候直接放入application级别的变量里,而不是每次request请求的时候都从request中获取,这样会比较耗费资源。public class ContextInitor implements ServletContextListener  {
private static final Logger log = Logger.getLogger(ContextInitor.class); @Override
public void contextDestroyed(ServletContextEvent arg0) {
CommonListener.doDestory();
} @Override
public void contextInitialized(ServletContextEvent arg0) {
CommonListener.doInitialize();

//设置application级别的变量
ServletContext application = arg0.getServletContext();
application.setAttribute("cacheRand", Math.round(Math.random() * 10000));
System.out.println(application.getContextPath());


}}我以上代码只能输出/project

解决方案 »

  1.   

    而不是每次request请求的时候都从request中获取,这样会比较耗费资源。你没发现生成的jsp页面总有个basePath吧,那会不会耗资源,你如果在启动tomcat时候就想获得这些信息?自己解析tomcat的server.xml吧。
      

  2.   


    HttpServletRequest request=ServletActionContext.getRequest();
    String path=request.getRequestURI();
    String actionPath=".."+path.substring(9);
    //访问服务器所带有的参数信息
    String queryInfo=request.getQueryString();
    if(queryInfo!=null&&(!queryInfo.equals(""))){
    actionPath=actionPath+"?"+queryInfo;
    }
    logger.debug("用户访问的路径是:"+actionPath);
    ActionContext.getContext().getSession().put(GlobalField.PRE_PATH, actionPath);