有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将getAttribute()scriptlet重写为JSP/HTML中的JSTL?

我的JSP页面中有一个scriptlet,它从上一个serlvet传递了一个属性“username”。scriptlet会验证是否设置了“username”属性,如果未设置,则会拒绝访问主页,并重定向到登录页面:

<%
    String validUser = (String) session.getAttribute("username");
    if (validUser == null){
    session.setAttribute("errorMsg", "Access Denied:  Please login to access this page");
    session.setAttribute("username", "");
    response.sendRedirect("LoginFormError.jsp");
        }
%>  

既然JSP/HTML代码中的scriptlet并不理想,我该如何将这个scriptlet重新编写为JSTL呢

编辑

好的,到目前为止,我得到的是:

<c:set var="validUser" value='${param.username}' />

<c:if test = "${validUser == null"}   
   <c:set var="errorMsg" value="${'Access Denied:  Please login to access this page'}"/>
   <c:set var="username" value=""/>
   <c:redirect url="LoginFormError.jsp"/>
</c:if>

getAttribute()和setAttribute()是否正确


共 (1) 个答案

  1. # 1 楼答案

    很高兴看到您这样做,您可以使用jstl/coretaglib

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    
    <c:if test="${sessionScope.username == null}">
        <c:redirect url="LoginFormError.jsp" />
    </c:if>