We're currently adding some new features to an old webapp which was using only JSP without any framework for the front. We have added Spring recently, and we would like to autowire our beans in our modified JSP, while not rewriting everything to use SpringMVC, Struts2 or Tapestry5.

We're using autowiring by type, so it leads to get some code like this in the JSP, while previously getting the web application context ( as "wap") :

the nice thing about SpringMVC is that you don't have to swallow the whole pill. You can pick the parts of spring you want to use. It would probably be cleaner to do what Stephen C indicated and start refactoring.
–
SWDJan 26 '10 at 13:54

4 Answers
4

HttpServletRequest decorator that
makes all Spring beans in a given
WebApplicationContext accessible as
request attributes, through lazy
checking once an attribute gets
accessed.

This would require your controller code to wrap the original HttpServletRequest in a ContextExposingHttpServletRequest, and then forward that to the JSP. It can either expose specific named beans, or every bean in the context.

Of course, this just shifts the problem from your JSPs to your controller code, but that's perhaps a more manageable problem.

What do you think about changing this to a filter (rather than a servlet) on top of JSPs which get all beans from Spring context and put them in the request scope, named by the expected interface in order to have a simili getByType ?
–
temsaJan 26 '10 at 14:22

Now, I'm not sure whether servlet containers are required to use only one instance of a servlet class. If not, you'd better place the above code in a getter-method for the dependency (getDao()) and if the @Autowired property is null (i.e. another instance of the servlet-class is used by the container) - perform the above operation.

That all said, really consider using a web framework (any of the ones you listed). Having logic in jsps is completely wrong, hard to support, hard to read, etc.

I definitively know, but you can't rewrite a whole software in 5 days(including splitting front and business logic), while adding new features. In fact we should avoid using the DAO there and write then rely only on the business object too, but this is just some already written code that I can't rewrite in such a few time. Convincing managers to convert the app to Spring/Hibernate/Jpa instead of home made singletons and company made ORM tools was already a great pain. They only see that as a cost...
–
temsaJan 26 '10 at 15:21

I think that the clean solution would be to start refactoring your code to get the business logic out of the JSPs, using either SpringMVC or one of the alternatives you cited.

Start with one or more minimalist controllers that simply pass the request to the JSPs with the injected beans as attributes; @skaffman's answer gives one way to do that, or you could do it more selectively. Then progressively migrate code out of the JSPs and into the controllers.