开发者

Best practice for referencing Java inside my JSPs

I'm asking for some opinions on referencing Java code (in my case an enum value) in a JSP.

I currently have conditional logic in my JSP like:

<c:if test="${actionBean.order.status eq 'complete'}">    
    show some stuff
</c:if>

Now, 'complete' is a value associated with an enum in my codebase. Would it be better to reference the enum inside my JSP? If so, how?

I think it might be a good thing because: If the enum changes, then the JSP doesn't break.

Is it bad practice to mix Java code into the JSPs? Or is it w开发者_如何学Goorse to duplicate the value of 'complete'?

Thanks in advance.


Is it bad practice to mix Java code into the JSPs? Or is it worse to duplicate the value of 'complete'?

My opinion is that you should avoid mixing Java code with JSPs, even if it means some limited duplication of symbols / values.

Think of it this way: there are many, many changes that could be made on the Java side that could "break" a JSP. In this case, for instance, the name of "actionBean", the getOrder() or getStatus() methods could change. Or getOrder() could return a null or something of a different type. If you worried about all of the things that could change on the Java side, you'd end up not using taglibs at all.


The enum value which you're comparing with in JSP is actually the same as String.valueOf(enum) and this is by default exactly the enum name. So if you change the enum's name, then you should really also change the JSP code. So I don't see any benefit to compare against the actual enum object. It would be coerced to String with String.valueOf(enum) as well and you would effectively end up comparing two Strings with each other. Just keep it as it is.

With regard to referencing Java code in a JSP file:

  • If you want to preprocess requests, use HttpServlet#doGet().
  • If you want to postprocess requests, use HttpServlet#doPost().
  • If you want to control the flow or output, use taglibs such as JSTL core.
  • If you want to invoke functions, use EL functions such as JSTL functions.

All the Java code which is (in)directly referenced in the HttpServlet can be breakdown further:

  • If you want to filter requests/responses, use a Filter class.
  • If you want to interact with a database, use a DAO class.
  • If you want to store/transfer/access data, use a Javabean (DTO) class.
  • If you want to execute business logic, use a Domain (BO) class (consider strategy pattern).
  • If you want to have/use reuseable static tools, use an Utility class (final class, private constructor).


Can't you do the logic for whether or not you want to "show some stuff" outside of the JSP and just pass a simple boolean parameter in to tell whether or not to display the stuff? That way you avoid duplicating the enum value and you also keep that bit of logic in the controller instead of in the view.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜