替换 scriptlet 以避免 .jsp 文件中的 java 代码
Replace scriptlet to avoid java code inside .jsp file
我将相同的 Java 小脚本复制并粘贴到多个 .jsp 文件中。
我想用更易于维护且可读性更好的解决方案来替换它
<%
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>
编辑:我在 FrenchFigaro 的回答后使用 JSTL 重写了代码。任何感兴趣的人的最终代码如下:
<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>
要替换if/else部分,您可以使用<c:if>
或<c:choose>
第一个提供单一选择,没有其他选择(但条件相反的两个标签就可以了)。
在你的情况下最好使用 <c:choose>
。
<c:choose>
<c:when test="${condition}">...</c:when>
<c:otherwise>...</c:otherwise>
</c:choose>
至于其余部分,您将需要使用一个 bean 在您的 servlet 和 JSP
之间传输数据
我将相同的 Java 小脚本复制并粘贴到多个 .jsp 文件中。 我想用更易于维护且可读性更好的解决方案来替换它
<%
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>
编辑:我在 FrenchFigaro 的回答后使用 JSTL 重写了代码。任何感兴趣的人的最终代码如下:
<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>
要替换if/else部分,您可以使用<c:if>
或<c:choose>
第一个提供单一选择,没有其他选择(但条件相反的两个标签就可以了)。
在你的情况下最好使用 <c:choose>
。
<c:choose>
<c:when test="${condition}">...</c:when>
<c:otherwise>...</c:otherwise>
</c:choose>
至于其余部分,您将需要使用一个 bean 在您的 servlet 和 JSP
之间传输数据