Sunday, January 22, 2012

Removing scriptlets from a JSP

I have read on internet that it is a very bad idea to use scriplets in a JSP.
Even if you need to use scriplets in a JSP, that is most likely because you are doing something in JSP, which should be better handled in a Action class.

So, I am trying to gather few tips, how to convert an existing JSP with scriplet to a JSP without scriplet.

Guys please comment and add more, i'll keep on adding it to the main post :)
There could be multiple ways of doing the same thing, you guys can add your knowledge to this, so that we can come up with a post, that we can re-use.

Most of the help has been taken from http://www.roseindia.net/jstl/jstlcoretags.shtml

You might like to read a discussion on WHY to avoid scriplets


Scriplet code Without scriplet code
<%=request.getContextPath()%> ${pageContext.request.contextPath}
<%= request.getRequestURI().contains("/events/")%> ${fn:contains(pageContext.request.requestURI, '/events/')}
<%= request.getRequestURI().contains("/events/") ? "class='selected'" : ""%> ${fn:contains(pageContext.request.requestURI, '/events/')? 'class="selected"' : ''}
<% if(request.getRequestURI().contains("/events/")) { %>

...

<%}%>
<c:if test="${fn:contains(pageContext.request.requestURI, '/events/')}">
...
</c:if>
<% String s = request.getParameter("text1"); %> <c:set var="s" value="${param.text1}" >
<% out.println(s);%> <c:out value="${s}" />
<% if(s.equals("sam"))
{
out.println("Good Morning...SAM!");
}
%>
<c:if test="${s eq 'sam'}">
<c:out value="Good Morning...SAM!" />
</c:if>

<%
switch(s)
{
case 1: out.println("Sunday");
case 2: out.println("Monday");
...
}
%>

<c:choose>
<c:when test="${s==1}">Sunday </c:when>
<c:when test="${s==2}">Monday</c:when>
<c:when test="${s==3}">Tuesday</c:when>
<c:when test="${s==4}">Wednesday</c:when>
<c:when test="${s==5}">Thursday</c:when>

<c:otherwise>
select between 1 & 5
</c:otherwise>
</c:choose>

<%
HttpSession session = request.getSession();
out.println(

(Questions)

session.getAttribute("Questions").getQuestionPaperID());

%>
<c:out value="${sessionScope.Questions.questionPaperID}" />

<%request.getSession().getAttribute("my_var") %>

Can be accessed using JSTL with the sessionScope keyword. To access my_var, call sessionScope.myvar

Remember to use sessionScope

<c:out value="${sessionScope.my_var}"/>

To make it easier, this link would help you understand the JSTL tags better...

3 comments:

  1. Replies
    1. Author of javakafunda.blogspot.com: Please do keep adding more...if u get to know.

      Delete
    2. Please do let me know if you get to know of any more about it.

      Yogesh Gandhi (Author of javakafunda)

      Delete