Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a custom VariableResolver in pure JSP

Tags:

java

jsp

el

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)

like image 272
fedd Avatar asked Feb 16 '11 13:02

fedd


2 Answers

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.

like image 132
BalusC Avatar answered Oct 03 '22 07:10

BalusC


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

like image 32
fedd Avatar answered Oct 03 '22 07:10

fedd