JS/ CSS files not found due to path differences java, spring mvc, velocity

落花浮王杯 提交于 2019-12-23 03:07:14

问题


I have this directory structure:

webapp
 - resources
   - custom.js
   - base.css
 - WEB-INF
 - views
   - layout.vm
   - top.vm
   - footer.vm
   - index.vm
   - FolderA
     - restricted.vm

My layout.vm is:

#parse('top.vm')
$screen_content
#parse('footer.vm')

My top.vm consists include these JS and CSS files:

<link href="resources/base.css" rel="stylesheet">
<script src="resources/custom.js"></script>

Now when my I access http://www.example.com:8080/index page, I see the JS and CSS files getting found. But when I visit http://www.example.com:8080/FolderA/restricted, JS and CSS files are not found. It works when in top I change it

But then the index page is broken.

I am using spring controllers to return the appropriate views. For e.g. The following returns the index page:

@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Model model) {       
    return "index";
}

and this returns the restricted view:

@Controller
@RequestMapping(value = "/FolderA")
public class SomeController {

    @RequestMapping(value = "", method = RequestMethod.GET)
    public String secured(Model model) {

        return "FolderA/restricted";
    }

Any suggestions as to how I can fix this issue?

On a side note, I was facing this issue when using regular jsp files as well, but I managed to fix it using <c:url ..>. I dont know how this can solved in velocity.


回答1:


thats because the resources you have declared are relative to the url used for accessing the view. You have to change all the static resource urls to absolute You can do this using tag

change from this

<script src="resources/custom.js"></script>

to

<script src="<c:url value="/resources/custom.js"/>"></script>

this should generate something like this in the HTML

<script src="<c:url value="http://www.example.com:8080/FolderA/resources/custom.js"/>">
</script>

Note But for this to work you should add %@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> to your jsp and include jst tag library into the webapp

Edit------

For the paths referred inside in JS and CSS files , there is a work around.Use base tag to define the absolute path tags in the HTML need to use

<base href="http://www.example.com:8080/FolderA/">


来源:https://stackoverflow.com/questions/15106978/js-css-files-not-found-due-to-path-differences-java-spring-mvc-velocity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!