0

I have a scriptlet within my JSP page that gets an attribute "username" passed from a previous serlvet. The scriptlet validates if the "username" attribute was set, if not it denies access to homepage and instead redirects to the login page:

<%
    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");
        }
%>  

Since scriptlets in JSP/HTML code is not ideal, how do I go about re-writing this scriptlet as a JSTL instead?

EDIT:

Ok, so far here's what I've got:

<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>

Are the getAttribute() and setAttribute() done right?

James McTyre
  • 103
  • 7

1 Answers1

0

Good to see you doing this, You can do using the jstl/core taglib

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

<c:if test="${sessionScope.username == null}">
    <c:redirect url="LoginFormError.jsp" />
</c:if>
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
  • I did an edit before I saw your answer. I'm wondering if `${param.attr["username"]}` is equivalent to `getAttribute("username")`? – James McTyre Nov 21 '18 at 00:37
  • I thought the `username` was a session variable as per your original post. Why don't you try what I have posted? – Scary Wombat Nov 21 '18 at 00:40
  • Ah, yes. Sorry about that, I was following a JSTL guide that had `attr` as the session variable. Yes, `username` is my correct variable. – James McTyre Nov 21 '18 at 00:42
  • What's the difference between `${param.username}` and `${sessionScope.username}`? A contributor suggests using `param` according to his answer here (2nd answer): https://stackoverflow.com/questions/4912690/how-to-access-at-request-attributes-in-jsp/44677068 – James McTyre Nov 21 '18 at 00:45
  • Yes, that was my understanding i.e. `username` would be part of the queryString, **but** your question posted it as `String validUser = (String) session.getAttribute("username");` which is a session variable. Only **you** can say which is correct. But anyway, please modify my answer as per your requirements. – Scary Wombat Nov 21 '18 at 00:47
  • Er, James what's happening? – Scary Wombat Nov 21 '18 at 01:43