开发者

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&开发者_开发问答gt;

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?


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

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


How about

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


You're setting the local host and port in the base path instead of the remote host and port.

This is after all not a nice construct to create the base path. I'd suggest to create it as follows instead:

path = request.getRequestURL().toString().replace(request.getRequestURI(), request.getContextPath()) + "/";

Or just nicely in JSTL/EL

<c:set var="r" value="${pageContext.request}" />
<base href="${fn:replace(r.requestURL, r.requestURI, r.contextPath)}/" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜