java - How to dodge duplication using EL? -
i'm rewriting .jsp scriplets jstl / el , i'm facing issue. it's simple i'm new el , bit lost.
here's i'm doing...
in servlet/controller:
final list<person> l = new arraylist<person>(); personlist.add(...); . . request.setattribute( "personlist", l );
and in .jsp:
<c:foreach var="person" items="${personlist}"> ${person.name} </c:foreach>
but i'm duplicating "personlist" because i'm using both in setattribute , in foreach. how can rid of duplication?
ideally i'd have constant, public static final string, reference both servlet , .jsp (using el, not scriptlets).
obviously reason want eliminate duplication if decide rename personlist to, say, persons (with 's'), need change 2 things , error-prone. if had constant, there 1 place i'd need make change.
edit commented using constant, there still need 2 places change if changed name of constant. there's big difference if this:
request.setattribute( constants.person_list, l );
then decide rename *person_list* , made typo, break @ compile time.
while if mistype:
request.setattribute( "persnlist", l ); // forgetting 'o' here
this lamely compile , fail @ runtime if .jsp using "personlist" , not mistyped "persnlist".
that's when working legacy/basic jsp/servlets. you're manually doing front controller tasks yourself.
move on real mvc framework. example jsf, spring mvc, wicket, etc. frameworks have single servlet (or filter) acts front controller doing nasty preprocessing job of creating beans, putting them in desired scope , on. end op working javabeans models , jsp/facelets files views. in example jsf need following javabean (which "automagically" set in request scope jsf itself):
@managedbean @requestscoped public class persons { private list<person> list; @ejb private personservice service; @postconstruct public void init() { list = service.list(); } public list<person> getlist() { return list; } }
and facelet view:
<ui:repeat value="#{persons.list}" var="person"> #{person.name} </ui:repeat>
no duplication , when using decent ide tools (e.g. eclipse jboss tools), linked each other can source > refactor > rename without pain.
Comments
Post a Comment