I am using Java EE with Spring framework. I have been setting up a test project (everything is working so far) and I currently have the following line in the controller to simply load up a view called index.jsp:
return new ModelAndView("index");
This is just a test project so I’m not worried about syntax or anything like that. I am simply wondering what is the best way to load up a certain view from within a controller in Spring? I am sure that hard-coding it like this is not best-practice and am just wondering what the proper way to do this is? Should the name be pulled from some config file?
The Spring pattern at work here is the
ViewResolver. Essentially, your controller returns the symbolic name of the view you want to forward to, and Spring resolves that symbolic name to an actual view. If you don’t configure it otherwise, then it’ll just stick.jspon the end and use that – simplest case.However, this can get as complex as you want it to, including, as you suggest, using a configuration file to map the names to actual JSPs. As always with Spring, there are a dozen different ways to do this – see this part of the docs.