How to add a custom VariableResolver in pure JSP
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 t开发者_JAVA技巧o 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)
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.
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
精彩评论