简体   繁体   中英

How do I access a model in JSTL outside of EL?

In Expression Language, I can access my model like so: ${model.member} How do I achieve the same thing when I want to use <%=some_method(${model.member}); %>

The reason is because I have some HTML helper methods I created to separate logic from UI, and I need to pass a member of the model to create the user control.

The JSP's main method has the following signature:

        _jspService(HttpServletRequest request,
                    HttpServletResponse response)
             throws ServletException, java.io.IOException

Based on this, you can access the request and response objects programattically from a scriptlet. For example:

        <%= request.getParameter("foo").toString() %>

or

        <%= request.getAttribute("bar").toString() %>

If you want to do something more complication, you could precede these with scriptlets to declare / initialize local (Java) variables; eg

        <% String foo = request.getParameter("foo") == null ?
                   "no foo" : request.getParameter("foo").toString(); %>

        <%= foo %>

You can use this to lookup your model in the request or response object (I think it will be an attribute of the request with name "model"), cast it to the appropriate type, and call its getter methods.


The reason is because I have some HTML helper methods I created to separate logic from UI, and I need to pass a member of the model to create the user control.

A better idea would be to turn those helper methods into custom JSP tags so that you can use them without resorting to scriptlets. JSPs with embedded scriptlets are generally thought to be hard to read and hard to maintain. One small mistake (or one change to the model API) and the JSP generates bad Java on your deployment platform and you get a broken page.

Take a look at JSTL custom functions. It allows a way for you to call static functions from your code in a JSTL standard way. You just need to set then up in your tld file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM