Tuesday, 17 December 2013

How to access css/js files in jsps or js file path in jsp context path

PROBLEM:
Project Structure is

webapp
   ||
   ||==css
   ||==images
   ||==js
   ||==WEB-INF

I have given
<link type="text/css" rel="stylesheet" href="/css/accordian.css" /> 
  
http://localhost:8080/--here it will be appended.

If I remove "/css " and place "css"

http://localhost:8080/EmployDetailsSpring/controller/userauthentication/login
It removes last appended string and places  css/accordian.css 
http://localhost:8080/EmployDetailsSpring/controller/userauthentication/css/accordian.css

SOLUTION:
Place project name before path.

    <img alt="" src="/EmployDetailsSpring/images/banner.png" />

EmployDetailsSpring is my Project name.

But if Project name changes its a headache to change all paths.To over come that we use
<%=request.getContextPath()%> which means Project name it self.

For IMAGE
  <img alt="" src="<%=request.getContextPath()%>/images/banner.png" />
For JS
<script type="text/javascript" src="<%=request.getContextPath()%>/js/cycle-plugin.js"></script>
For CSS
<link type="text/css" rel="stylesheet" href="<%=request.getContextPath()%>/css/accordian.css" />

above one means same but if Project name changes we dont need to change manually.

No comments: