tags:

views:

101

answers:

1

Hey everyone,

So my setup for my web application is that I have a general header and footer and then I just include them in all my other pages so that all the common elements for all the pages are in a single page. The only problem I'm running into is when I want to redirect the user back to a login page if the "username" session has not already been created.

The problem that I"m running into is that I have an if statement at the top of my header.jsp and then I have the else in the footer.jsp and it is giving me a java syntax error. Any ideas? Here is the code I'm referring to...

    <%@page contentType="text/html" pageEncoding="UTF-8"%>

<% 
if(session.getAttribute("username") != null)
{
%>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">


<!--  CSS files -->
<link rel="stylesheet" href="../CSS/headerStyle.css" type="text/css" media="screen" />


<title>Insert title here</title>
</head>
<body>

<div id="container">
<div id="header">
<div id="headerTitle">Title</div>
</div>
</div>
<%} %>

And then here is the footer

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                       "http://www.w3.org/TR/html4/loose.dtd"&gt;

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../CSS/headerStyle.css" type="text/css" media="screen" />

</head>
<body>

<div id="footer"></div>

</body>
</html>

<% 
else
{
    response.sendRedirect("../wa_login/login.jsp");
}
%>

However it is giving me an error on the else statement because the else doesn't have an if statement because it's in the header file.

+3  A: 

Each .jsp has to compile as an independent unit. Hence the error.

Why not just perform the check in the header and redirect from there ?

<% 
if(session.getAttribute("username") == null)
{
response.sendRedirect("../wa_login/login.jsp");
}
%>
Brian Agnew
Add a `return;` statement. Else the server logs will get cluttered with `IllegalStateException` s when a redirect has occurred. Also, you must at that moment be lucky if the response isn't already committed. The right approach would be a `Filter`. This doesn't belong in a JSP :)
BalusC