How to keep logic out of a JSP?

This question already has an answer here:

  • How to avoid Java code in JSP files? 28 answers

  • One way to do this is to write a function that lives inside the bean class, or perhaps more properly inside a wrapper for the bean class:

    public class BeanFormatter {
    
      private Bean bean;
    
      public BeanFormatter(Bean myDataBean) {
        this.bean = myDataBean;
      }
    
      public String getFormattedHTML() {
        //put your logic here. Return the necessary HTML based on the bean.
      }
    }
    

    It's possible that what you want to return is not HTML in format of a String, but a div name or other css class to wrap the data in. But you could just write another method such as getDisplayCSSClass() .


    您可以创建一个“翻译器”对象,该对象具有一个(或多个)采用bean的方法,并返回格式化的HTML。


    In case that you need to have some special behavior on view, and you want to keep clean JSPs you should consider creating of new tag. You should know that there is few different kinds of tags. And because your tag is responsible for creating visual component i would suggest usage of tag files.

    Check this tutorial to get base idea how it is working.

    链接地址: http://www.djcxy.com/p/76596.html

    上一篇: JSP访问全局变量

    下一篇: 如何保持逻辑脱离JSP?