开发者

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

In Expression Language, I can acc开发者_开发技巧ess 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; e.g.

        <% 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜