Thursday, September 19, 2019

java - How to avoid using scriptlets in my JSP page?



I've been told that the use of scriptlets (<%= ... %>) in my JSP pages isn't such a great idea.



Can someone with a bit more java/jsp experience please give me some pointers as to how to change this code so its more 'best practice', whatever that may be?



This JSP is actually my sitemesh main decorator page. Basically my web design has a tab strip and a submenu, and i wish to somehow highlight the current tab and show the correct submenu by looking at the current request URI.



<%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator" %>




My Events - <decorator:title />

















Thanks all


Answer



I think it helps more if you see with your own eyes that it can actually be done entirely without scriptlets.




Here's a 1 on 1 rewrite with help of among others JSTL (just drop jstl-1.2.jar in /WEB-INF/lib) core and functions taglib:



<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>



My Events - <decorator:title />











Here's a more optimized rewrite, note that I used c:set to "cache" expression results for reuse and that I use HTML tag to avoid putting the context path in every link (just make all relative URL's in your webpage relative to it --without the leading slash!):



<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>







My Events - <decorator:title />











It can actually be optimized more if you collect all those "hardcoded" values like events and people and link texts in a Map in the application scope and use under each the JSTL to display the tabs.



As to your actual question, you can disable scriptlets (and get runtime errors about using it) by adding the following entry in webapp's web.xml. It may help to spot overseen scriptlets.






*.jsp
true




To learn more about EL, check the Java EE tutorial part II chapter 5. Implicit EL objects, such as ${pageContext} are described here. To learn more about JSTL, check the Java EE tutorial part II chapter 7. Note that JSTL and EL are two separate things. JSTL is a standard taglib and EL just enables to access backend data programmatically. Although it is normally used in taglibs like JSTL, it can also be used standalone in template text.


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...