?
Servlets & JSP Series 9 - Custom tags are powerful
?
- Using the c:out tag to render the text of users prevents cross-site hacking of this form by displaying the <script> tags and the JS code in other user’s web browser, this prevents the JS code from being interpreted by the browser, foils the attack from the user.
- <c:out> also can set default value with the default attribute.
- <c:forEach> tag from the JSTL is perfect – it gives us a simple way to iterate over arrays and collections.
- The <c:forEach> tag maps nicely into a for loop – the tag repeats the body of the tag for each element in the collection ( and we use “collection” here to mean either an array or Collection or Map or comma – delimited String), the key feature is that the tag assigns each element in the collection to the variable you declare with the var attribute, varStatus makes a new variable that holds an instance of java.servlet.jsp.jstl.core.LoopTagStatus, the LoopTagStatus class has a count property that gives you the current value of the iteration counter.
- Also we can even nest <c:forEach> tags.
- The <c:choose> tag and its partners <c:when> and <c:otherwise> can be used when you need an else.
- The <c:set> tag is much cooler than <jsp:setProperty>, it can set a value in a Map; set comes in two flavors: var and target. The var version is for setting attribute variables, the target version is for setting bean properties or Map values, each of the two flavors comes in two variations: with or without a body, the <c:set> body is just another way to put in the value, if the value evaluates to null, the variable will be removed.
- Key points and gotchas with <s:set> : 1.You can never have both the “var” and “target” attributes in a <c:set>; 2.”Scope” is optional, but if you don’t use it the default is page scope; 3.If the “value” is null, the attribute named by “var” will be removed; 4.If the attribute named by “var” does not exist, it will be created, but only if “value” is not null; 5.If the “target” expression is null, the Container throws an exception; 6.The “target” is for putting in an expression that resolves to the Real Object, if you put in a String literal that represents the “id” name of the bean or Map, it won’t work, in other words, “target” is not for the attribute name of the bean or Map – it’s for the actual attribute object; 7.If the “target” expression is not a Map or a bean, the Container throws an exception; 8.If the “target” expression is a bean, but the bean does not have a property that matched “property”, the Container throws an exception, remember that the EL expression ${bean.notAproperty} will also throw an exception.
- <c:remove> is used for removing an attribute.
- The <c:import> JSTL tag dynamically adds the content from the value of the URL attribute to the current page, at request time, it works a lot like <jsp:include>, but it’s more powerful and flexible.