开发者

Hardcoding view names in the controller alternative?

开发者 https://www.devze.com 2022-12-18 03:11 出处:网络
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

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 .jsp on 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.


If you're using SimpleFormControllers, you can set a formView and a successView. The formView is returned on a GET request, and the successView is returned by default if everything succeeds in the PUT request.


In my last Spring 3.0 web app I used a combination of:

  1. Constant String fields in my Controller class for view names

  2. A properties files with values that override field values that are injected by Spring via "context:property-override" configuration:

<context:property-override location="classpath:viewName.properties"/>

In order for the latter to work you have to either list all the controllers as beans in the dispatcher XML configuration file OR annotate your controller with the @Component("fooController") (edit: not sure if @Controller("fooController") will work instead?) annotation and then reference the fields in the properties file like this: fooController.someView=someJsp.

Not sure if it is "best practice" but it works well enough for me. I make sure I add comments to the Controller class fields telling future developers to look for the overrides in the property file.

0

精彩评论

暂无评论...
验证码 换一张
取 消