Spring 3 - Enable javascript via JSP view resolver?

I am trying to localize my application, and it would be nice if I could just send all the JS files through the JSP converter to gain access to the localization packages.

Right now I have this:

<bean id="viewResolver" class= "org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> 

and I was wondering if there is an easy way to enable .js and .jsp via InternalResourceViewResolver without adding some patterns to the hacking.

+4
source share
2 answers

You really don't need your .js files to be stored as .js if their content type is text/javascript . But having dynamic information in your .js files is wrong:

  • you cannot cache them correctly
  • you may be tempted to add jsp logic to your .js file, which will be difficult to maintain
  • you cannot use competing networks (if necessary)
  • (and maybe there are other flaws that I can't think of right now)

Instead, you should initialize some settings object from the jsp page that uses the .js file. See this answer for more details.

Here is a specific (simplified) example from my code. This snippet is in .jsp :

 <script type="text/javascript"> var config = { root : "${root}", language: "${user.language.code}", currentUsername: "${user.username}", messages : { reply : "${msg.reply}", delete : "${msg.delete}", loading : "${msg.loading}", } }; init(config); </script> 

init(config) is in the .js file and simply sets the configuration object as a global variable. (Actually, I have default values, but that doesn't matter)

+8
source

Put all your javascripts under webapp/scripts . Then programmatically add this implementation of the addResourceHandlers() method to your WebConfig.xml:

 @Configuration @EnableWebMvc @ComponentScan(basePackages = "package.base.your") public class WebConfig extends WebMvcConfigurerAdapter { //your other WebMvcConfigurerAdapter class implementations here @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //other handlers here registry.addResourceHandler("/scripts/**").addResourceLocations("/scripts/**"); } 
0
source

Source: https://habr.com/ru/post/1346807/


All Articles