javaGirl243 javaGirl243 - 1 year ago 39
AngularJS Question

How to load Spring MVC view without reloading js files in it

I have 3 JSP views which all use the same JS file(say app.js).

My UI is on AngularJS which has a different controller for each of the JSP views and also has a custom service which shares information between the controllers. When I load the first JSP, its controller specified in the app.js file saves a value in the custom service. When I load the next JSP file, app.js gets reloaded and so the value that was saved in the custom service is lost.

Is there a way to not re-load JS files? Or is there a better way to go about this?

Answer Source

Javascript variable are not automatically preserved. When you open a new URL in your browser, you do not download again the JS files (they are cached), but they are loaded from scratch in that new page. That means that all previous values are lost, not by accident but by design.

You have different ways to deal with this persistence between page question. One way is server side by using the session:

  • the js part sends the value to save as parameters of a request
  • a spring-mvc controller puts that in the session
  • other views (jsp) or controllers (spring) access the saved value and pass it in the responses

An alternate way is the single page application pattern:

  • you only load one single full page from the server
  • the javascript then only sends requests that it processes directly to modify the DOM

Additionally, you could use Windows.sessionStorage to store data client side for the duration of a client session - credits should go to @AmitParashar for this one, more details in his answer.

You can of course mix the 2 patterns (this is commonly done in real world applications), but you must know that every page load will erase all client javascript state

A less common pattern (AFAIK) is to put the state in a cookie. That way it can be shared by the server and the client but:

  • it is limited to 4k size
  • you cannot use it for server side security, because it can too easily be forged