Umesh Awasthi
Umesh Awasthi

Reputation: 23587

Context Path and static content | Spring Boot

I am trying to port my application to Spring boot and things are working fine for me. I am facing issue with static content and contextPath. I have added following property in my application.properties

server.contextPath=/sm-admin

before this, I was referring to my static contents by

<script src="/plugins/jQuery/jquery-2.2.3.min.js"></script>
<script src="/bootstrap/js/bootstrap.min.js"></script>

but with addition of contextPath, above configuration is no longer working and I have following way

Change static content references to

 <script src="../plugins/jQuery/jquery-2.2.3.min.js"></script>
 <script src="../bootstrap/js/bootstrap.min.js"></script>

Or

I believe there should be some way to handle it using application.properties file but I am unable to find such configuration. Can some on point me to right direction.

Upvotes: 0

Views: 3498

Answers (2)

Aviral
Aviral

Reputation: 61

In your index.html, change <base href="/"> to <base href="./">.

This solved my problem.

Upvotes: 2

artemisian
artemisian

Reputation: 3106

There are 2 factors in this problem: your web app and the browser, so I don't think this can be controlled through Spring since this has to do with the browser's behavior.

Problem

In your 'old' html file version your app root context was /. That's why src='/plugins/jQuery/jquery-2.2.3.min.js' loaded without any issues.

Now since your app root context was changed to /sm-admin your web app will serve only request prefixed with that path. That's why src='/plugins/jQuery/jquery-2.2.3.min.js' doesn't work, your server will have responded fine if the it were src='/sm-admin/plugins/jQuery/jquery-2.2.3.min.js'

Now src='../plugins/jQuery/jquery-2.2.3.min.js' is working b/c your page must have been served from 1 folder below the root context, ie: /sm-admin/page/mypage.html and with .. you are just referencing the root path indirectly.

My proposed solutions:

  1. Prefix all resources loaded from the root with /sm-admin.

Or

  1. Change all absolute paths to relatives path, ie: change src='/plugins/jQuery/jquery-2.2.3.min.js' to src='plugins/jQuery/jquery-2.2.3.min.js' and set the base url in your header for all your relatives path, ie: <base href="/sm-admin/"/>. One caveat of this solution is that anywhere in your app you are using relative paths they'll become relative to this base path.

Upvotes: 3

Related Questions