How to add a custom VariableResolver in pure JSP
Asked Answered
E

2

5

I'd wish to programmatically add a custom VariableResolver when JSF or anything like that is not used, so that before seeking for beans in scopes as mentioned in 1, the EL would first try to resolve variables within it.

The goal is to make objects in the database available in EL right by their names, and there could be a lot of them to put into some scope.

Right now I put a special bean into the session scope under the name, say, 'z', and that bean extends Map interface and thus lets access the objects with expressions like ${z.address}, ${z.fullName}. I'm trying to eliminate that 'z'.

Better if I manage to insert my resolver in a Filter (sure i'll check not to do this multiple times for every web request)

(Edit: maybe I am talking about ELContext, how to put there my own VariableMapper or ELResolver or something like this)

Emulsifier answered 16/2, 2011 at 13:23 Comment(3)
I think i'll end with a simple solution. In Filter I have a request; I'll wrap it overriding getAttribute method and pass further!Emulsifier
When doing this, remember not to accidentally make unavailavle all the useful attributes set by servlet container in application and session contexts!Emulsifier
well, if you have found your solution, you should answer your own question and accept your own answer.Damask
C
8

You can register your custom ELResolver as follows.

@WebListener
public class Config implements ServletContextListener { 

    @Override 
    public void contextInitialized(ServletContextEvent event) {
        ServletContext servletContext = event.getServletContext(); 
        JspApplicationContext jspContext = JspFactory.getDefaultFactory().getJspApplicationContext(servletContext); 
        jspContext.addELResolver(new YourELResolver()); 
    } 

    // ... 
}

Note: this approach requires Servlet 2.5/JSP 2.1 or newer.

Chic answered 4/3, 2011 at 13:18 Comment(2)
this seems as the correct answer to what i have asked. no time to try, but accept! thanksEmulsifier
OMG! This is great! I was searching for it! Thanks BalusC!Chromic
E
1

I am going to wrap a request object, override getAttribute method, where I can return the needed value.

In normal situations, when an attribute is not found by it's name in the request context, the servlet container goes upper to the application and session contexts. There are kept some useful parameters.

To get sure not to override attributes set in application and session contexts, the wrapper should check them first and return them if they are set; otherwise, it would return what I wanted in the initial post.

I didn't check that, but sure it'll work

Emulsifier answered 4/3, 2011 at 11:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.