The initial JSTL 1.0 EL lacked support for functions. The JSP 2.0 EL lets you call a Java class's public static method using the following syntax: ${prefix: ...
CloseAd
infoworld
UNITEDSTATES
UnitedStates
UnitedKingdom
Welcome!HerearethelatestInsiderstories.
Howtoevaluatesoftwareassetmanagementtools
Howtochoosetherightdatavisualizationtoolsforyourapps
30topSaaScompaniesforbusiness
What’snewinKubernetes1.22
MoreInsider
SignOut
SignIn
Register
SignOut
SignIn
Register
NEWInsiderPRO
LearnMore
LatestInsider
Rusttutorial:GetstartedwiththeRustlanguage
GetstartedwithAnacondaPython
11tipsforspeedingupPythonprograms
Review:7PythonIDEsgotothemat
NEWFROMIDG
LearnMore
Welcome!CheckoutthelatestInsiderstorieshere.
SignOut
SignIn
Register
MorefromtheFoundryNetwork
AboutUs|
Contact|
RepublicationPermissions|
PrivacyPolicy|
CookiePolicy|
MemberPreferences|
Advertising|
FoundryCareers|
AdChoices|
E-commerceLinks|
California:DoNotSellMyPersonalInfo|
FollowUs
×
Close
ThenewJavaServerPages(JSP)versionincorporatestheexpressionlanguage(EL)introducedbytheJSPStandardTagLibrary(JSTL)toletWebdesignersproducescriptlessJSPpagesthatdon'tcontainJavacode.SinceJSP2.0providesbackwardcompatibilitytoJSP1.x,youmaystillincludeJavasnippetsinyourpages,buttaghandlersandJavaBeancomponentsaremuchbetterplacesforJava-basedfunctionality.JSP2.0providesnewfeaturesfortaghandlerssuchasdynamicattributes,theSimpleInvocationProtocol,and.tagfiles.YoustillusetheoldJSP1.0standardactionsforcreatingJavaBeaninstancesandsettingtheirproperties,butnowyoucanaccessbeanproperties,requestparameters,andJSPattributes/variableswiththenewexpressionlanguage.AllthoseJSPtechnologyimprovementsletyouachievethegoalofseparatingtheJSP/HTMLmarkupfromtheJavacode.Onethingismissing,however.JSP2.0hasnosyntaxforcallingapublicnonstaticJavaBeanmethodfromascriptlessJSPpage.ThisarticlesolvesthatissuebyprovidingaJSP2.0simpletagwithdynamicattributes.
Note:Youcandownloadthisarticle'ssourcecodefromResources.ExpressionlanguageneededSupposeyouhaveajava.util.ListinstanceyoumustpresentasanHTMLlist.HereisaquicksolutionbasedonJSP1.x:
ExistingJSP-basedWebapplicationsconsistofJavacodemixedwithHTMLmarkupliketheabovecodefragment.MaintaininghundredsofpageslikethatcanbeanightmareifyouhaveseparateJavadevelopmentandWebdesignteams.ThesolutionistomovetheJavacodeintotaglibrariessothatdeveloperscandotheirjobswithoutpastingJavacodewithinWebpagesanddesignerscanedittheirWebpageswithoutworryingaboutbreakingtheJavacode.However,JSP1.xhasseveralproblemsthatdon'tletyoueasilydevelopscriptlessJSPpages.Untilrecently,nostandardmethodexistedforaccessingJavaobjectsfromaJSPpagewithoutusingJavacode.Inaddition,codingtaghandlerclasseswasn'tassimpleasitcouldhavebeen.ThefollowinglinesofcodearebasedonJSTL1.0,whichcanbeusedwithJSP1.2.The
tagiteratesovertheelementsofthegivenlistandexportstheelemvariableforeachelement.Insteadofdeclaringelemasalocalvariable,thetagcreatesapageattributewithpageContext.setAttribute().Thisattribute'svalueisprintedwithJSTL'stag:
JSTLprovidesstandardtagsforprocessingXMLdocumentsandaccessingrelationaldatabasesalongwithformattingtags,internationalizationtags,conditionaltags,iteratortags,URL-relatedtags,andothergeneral-purposetags.JSTLhassolvedmanyofJSP1.x'sproblemswiththehelpofanexpressionlanguagethatallowsyoutoaccessJavaobjectsfromJSPpageswithoutusingJavacode.Forexample,insteadoflookingforanattributeoraccessingarequestparameterwith:
youmaynowuse:${a}
${param.p}
YoucanaccesstheJSPpagecontextobjects,page/request/session/applicationattributes(alsoknownasJSPvariables),JavaBeanproperties,collectionelements,requestparameters,initializationparameters,cookies,andHTTPheaders.WithJSP1.2,theexpressionlanguageisavailableonlytoJSTL-basedapplicationsandtaglibraries.JSP2.0makestheELavailabletoallJSPapplicationsandalltaglibraries(includingtheoldtaglibsdesignedforJSP1.x).JSP2.0alsosimplifiestaglibrarydevelopment,asyou'llseelaterinthisarticle.Sinceitsfirstversion,JSPhasprovidedstandardtagsforusingJavaBeansinJSPpages.YoucancreateorfindJavaBeaninstanceswith,andthenyoucangetandsettheirpropertieswithand.WithJSP2.0,youmayalsogetthevalueofapropertywith:${bean.property}
Inadditiontoproperties,JavaBeancomponentshavepublicmethodsthatoftenmustbecalledfromJSPpages.TheremainderofthisarticlewillpresentthreewaysforcallingJavaBeanmethodswithoutusingJavacode.OneisbasedontheJSP2.0supportforfunctions,whichareELconstructsthatallowyoutocallJavaclasses'staticmethods.Anothersolutionusescustomtagsthatgetthemethodparametersastagattributes.ThethirdwayisbasedonagenerictagthatletsyoucallanypublicmethodofanyJavaBeanclassfromaJSPpage.UsefunctionsTheinitialJSTL1.0ELlackedsupportforfunctions.TheJSP2.0ELletsyoucallaJavaclass'spublicstaticmethodusingthefollowingsyntax:${prefix:methodName(param1,param2,...)}
TheJSPfunctionmustbedeclaredinataglibrarydescriptor(TLD):
methodName
className
returnTypemethodName(param1Type,param2Type,...)
TheJavaclassdoesn'thavetoimplementanyspecialinterface.TheonlyrequirementistomaketheJavamethodpublicandstatic.TheTestBeanclassTheTestBeanclasshasapublicmethodnamedtestMethod(),whichiscalledfromtheJSPpagespresentedinthefollowingsections.TheJavaBeanhasthreepropertiesnamedtext,number,andlogic.ThesepropertiesaremodifiedbytestMethod(),whichreturnsastringcontainingthethreeproperties'modifiedvalues:packagecom.devsphere.articles.calltag;
publicclassTestBean{
privateStringtext;
privateintnumber;
privatebooleanlogic;
publicTestBean(){
text="";
number=0;
logic=false;
}
publicStringgetText(){
returntext;
}
publicvoidsetText(Stringtext){
this.text=text;
}
publicintgetNumber(){
returnnumber;
}
publicvoidsetNumber(intnumber){
this.number=number;
}
publicbooleangetLogic(){
returnlogic;
}
publicvoidsetLogic(booleanlogic){
this.logic=logic;
}
publicStringtestMethod(Stringtext,intnumber,booleanlogic){
setText(getText()+text);
setNumber(getNumber()+number);
setLogic(getLogic()||logic);
StringBufferbuf=newStringBuffer();
buf.append(getText());
buf.append('');
buf.append(getNumber());
buf.append('');
buf.append(getLogic());
returnbuf.toString();
}
}
TheTestFunctionclassBecausetheJSP2.0ELallowsonlycallstostaticmethods,TestBean'stestMethod()mustbewrappedinastaticmethod.TheTestFunctionclassprovidessuchastaticwrapperthattakesthesameparametersasthebeanmethodplusthebeanobjectwhosemethodmustbecalled:packagecom.devsphere.articles.calltag;
publicclassTestFunction{
publicstaticStringtestMethod(TestBeanobject,
Stringtext,intnumber,booleanlogic){
returnobject.testMethod(text,number,logic);
}
}
ThecompiledTestFunction.classfilemustbeplacedtogetherwithTestBean.classintotheWebapplication's/WEB-INF/classesdirectory.Asanalternative,thetwoclassfilescanbepackedinajarfileandstoredin/WEB-INF/lib.TheTestFunctionJSPBeforecallingthetestMethod()function,theTestFunction.jsppagemustspecifythefunction'sprefixandthelibrary'sUniformResourceIdentifier(URI):
ThetagcreatesaninstanceoftheTestBeanclass:
ThetestMethod()functioniscalledtwice.Thefirstcallgetssomeconstantparameters,whilethesecondcallgetsthevaluesofthebeanpropertiesasparameters:
${tf:testMethod(obj,"abc",123,true)}
${tf:testMethod(obj,obj.text,obj.number,obj.logic)}
TheTestFunction.jsppageproducesthefollowingHTMLoutput:
abc123true
abcabc246true
TheTestFunctionTLDAsmentionedearlier,theJSPfunctionmustbedeclaredinataglibrarydescriptor.TheTestFunction.tldfiledefinessomeversionnumber,thetfshortnameusedinJSPpagesasprefixfortestMethod(),thelibrary'sURI,thefunction'sname,thenameoftheclasscontainingthestaticmethod,andthemethod'ssignature.TheURIdoesn'thavetopointtoanexistingWebresource,butitmustbeunique.YoumaynotusethesameURIfortwodifferenttaglibraries.HereistheTestFunction.tldfile'scontent:
1.0
tf
http://devsphere.com/articles/calltag/TestFunction.tld
testMethod
com.devsphere.articles.calltag.TestFunction
java.lang.StringtestMethod(
com.devsphere.articles.calltag.TestBean,
java.lang.String,int,boolean)
TheTestFunction.tldfilemustbeplacedintotheWebapplication's/WEB-INFdirectory.Thesamedirectoryalsocontainstheweb.xmlapplicationdescriptor,whichdeclaresthelibrarywithinaelement.TheURIthatidentifiesthelibraryinJSPpagesandtheTLDfile'slocationarespecifiedwithintwoseparateXMLelements,and:
http://devsphere.com/articles/calltag/TestFunction.tld
/WEB-INF/TestFunction.tld
UsecustomtagsTaglibrarieswereintroducedbyJSP1.1,whichdefinedtheTagandBodyTaginterfaces.JSP1.2addedIterationTagandsupportforcatchingexceptions.TheseinterfaceshavehandlermethodssuchasdoStartTag(),doInitBody(),doAfterBody(),anddoEndTag().Onceyouunderstandhowthesemethodsshouldbeimplemented,it'seasytobuildtaglibraries.However,manydevelopersviewedJSP1.x'stag-handlingmechanismasunnecessarilycomplex.JSP2.0introducedamuchsimplertag-handlingprotocol.IfyouextendtheSimpleTagSupportclass,youjusthavetoimplementthedoTag()methodforhandlingaJSPtag.TheTestMethodTagclassTheTestMethodTag.jsppagecallsthetestMethod()JavaBeanmethodusingthefollowingsyntax:
WhentheapplicationservertranslatestheJSPpageintoaservlet,theabovetagisreplacedwithaJavacodefragmentthatcallsthemethodsofaTestMethodTaginstancecreatedforhandlingthetag.ThetaghandlerextendstheJSP2.0API'sSimpleTagSupportclassanddefinesonefieldforeachattribute.Thesefieldswillmaintainthetagattributes'values:packagecom.devsphere.articles.calltag;
importjavax.servlet.jsp.JspException;
importjavax.servlet.jsp.JspWriter;
importjavax.servlet.jsp.tagext.SimpleTagSupport;
importjava.io.IOException;
publicclassTestMethodTagextendsSimpleTagSupport{
privateTestBeanobject;
privateStringtext;
privateintnumber;
privatebooleanlogic;
Foreachtagattribute,theremustbeasetmethod,whichgetstheattributevalueandstoresitinafieldsothatthetaghandlercanuseitlater:publicvoidsetObject(TestBeanobject){
this.object=object;
}
publicvoidsetText(Stringtext){
this.text=text;
}
publicvoidsetNumber(intnumber){
this.number=number;
}
publicvoidsetLogic(booleanlogic){
this.logic=logic;
}
Aftersettingthetaghandler'sattributes,theJavafragment(resultingfromtheJSPtag)invokesthetaghandler'sdoTag()method,whichcallsthebeanmethod.ThedoTag()methodprintsthestringvaluereturnedbytestMethod().Therefore,theJSPoutputcontainsthereturnedvalue:publicvoiddoTag()throwsJspException,IOException{
Stringret=object.testMethod(text,number,logic);
JspWriterout=getJspContext().getOut();
out.println(ret);
}
}
TheTestMethodTag2classSupposeyouwanttousethevaluereturnedbythebeanmethodinaJSP.Forexample,youmighthavetopassitasanattributevaluetoanothertag.Or,youmightwanttocontrolitsoutputintheJSPpage:
...${ret}...
Related:
WebDevelopment
Java
1
2
3
Page1
Next
Page1of3
Howtochoosealow-codedevelopmentplatform