Saturday 17 August 2019

java - How to keep logic out of a JSP?




I need to build a table in a JSP.
I have an arraylist with a bunch of beans, and the beans were made from a resultset, just from the rows returned from a DB call.




Depending on the data, I want to show different things.
An example would be, if the name in the bean starts with 'a', highlight the name, if it starts with 'b', make the name red but not highlighted (i think that covers my question/situation).



If I do not have logic in the JSP, how would I control this?


Answer



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().


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...