Search code examples
jspservletspathradix

basepath in jsp


In my application,I use the struts2,and I create a base action to slove the path problem:

class BaseAction{
  private String path;
  static{
  HttpServletRequest request = ServletActionContext.getRequest(); path=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();+"/";
  }
}

Then all other action extend this baseaction.

In my jsp page,I add the path as the base:

xx.jsp:

....
<head>
  <base href="<s:property value='path'/>">
  <script ... src="res/test.js" />
</head>

It works well in my own machine.

http://localhost:8080/app The test.js canbe found by "http://localhost:8080/app/res/test.js"

But when other people try to visit my app,they use:

http://192.168.x.x:8080/app.

now,the browser still try to download the test.js by "http://localhost:8080/app/res/test.js"

Of course,it can not get it. The real path should be: http://192.168.x.x:8080/app/res/test.js

SInce, the "path" is hard code in teh action,any idea to fix this?


Solution

  • In a static initialization block I wouldn't expect you to have a request available. I'd do:

    <base href="${request.contextPath}" />