Home:ALL Converter>how to define a constant String in spring framework and use in JSP?

how to define a constant String in spring framework and use in JSP?

Ask Time:2012-09-21T20:57:37         Author:Mahdi

Json Formatter

I want to check if a specific item is selected in a drop-down menu. Suppose I have something like this in my JSP:

<sf:select path="xItem" >
    <sf:option value="val1" />
    <sf:option value="val2" />

and in my corresponding java bean, I want to check it as

if (xItem.equals("val1")) xItem = doSomething();

but, if I define "val1" as a constant, i.e., final static String mytext="val1", and change my jsp file as <sf:option value="${MyClass.mytext}" />, Spring will complain that mytext is not a property of MyClass. Is there anyway to define this text as a constant and refer to it in JSP and the corresponding Java class?

Author:Mahdi,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/12531064/how-to-define-a-constant-string-in-spring-framework-and-use-in-jsp
Bogdan :

The ${MyClass.mytext} expression applies to beans and properties, specifically it means that the server is expecting to find a bean saved in the current context as MyClass and on that bean to call a getter called getMyText (it's a jspContext.FindAttribute) which isn't the case here since you have a static member on a class.\n\nHere are some workarounds off the top of my head:\n\n\nuse a scriptlet and refer to the static member (if you can live with having scriptlets inside your JSPs);\nsave the value in your controller under some key inside your model and refer it in your JSP by that key;\ndefine a custom tag that given a class name and static member invokes it and places it under some key in page scope and you can use if from there (see an example in this article: Scriptless JSP Pages: The Constant Constants Consternation);\ndefine an EL function that returns the value of the constant (see an example in the same article Scriptless JSP Pages: The Constant Constants Consternation, scroll to the end of it).\n\n\nI would personally go with defining an EL function if you refer to constants often in your JSPs or set it under some model key in the controller if it's a one time only use.",