I have the same Java scriptlet copied and pasted into multiple .jsp files. I would like to replace it with a solution that's easier to maintain and has better readability
<%
if (!MediaUtil.validateAuthorization()) {
out.println("Unauthorized");
} else {
String srcquery = request.getQueryString();
if (srcquery == null) {
srcquery = "";
}
User currentUser = UserService.findCurrentUser();
if (currentUser == null) {
out.println(User.MESSAGE_NO_USER);
} else {
%>
<html>
<head>
EDIT: I have rewritten the code using JSTL after FrenchFigaro's answer. Final code for anyone interested is below:
<c:choose>
<c:when test="${!MediaUtil.validateOrganization()}">
<c:out value="Unauthorized"/>
</c:when>
<c:otherwise>
<c:set var="srcquery" value="<%=request.getQueryString()%>"/>
<c:choose>
<c:when test="${srcquery == null}">
<c:set var="srcquery" value=""/>
</c:when>
</c:choose>
<c:set var="currentUser" value="<%=UserService.findCurrentUser()%>"/>
<c:choose>
<c:when test="${currentUser == null}">
<c:out value="<%=User.MESSAGE_NO_USER%>"/>
</c:when>
<c:otherwise>
<html>
(...)
</html>
</c:otherwise>
</c:choose>
</c:otherwise>
</c:choose>
To replace the if/else part, you can use <c:if>
or <c:choose>
The first one provides a single choice and no else (but two tags with opposite conditions will do the trick).
Better to use <c:choose>
in your case.
<c:choose>
<c:when test="${condition}">...</c:when>
<c:otherwise>...</c:otherwise>
</c:choose>
As for the rest, you will need to use a bean to transfer the data between your servlet and the JSP