javajsp

How do I check if variable exists in a jsp page includes by another page


Usually my jsps contain the following at the start

<%@ page contentType="text/html"%>
<%@ page errorPage="error.jsp"%>
<%! String language ="en"; %>    
<%@ include file="/layout/inc/pagestart.jsp" %>

and pagestart.jsp contains

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="<%=language%>">

which works fine.

But if the main jsp doesnt include the language variable defn then compilation fails with

An error occurred at line: 2 in the jsp file: /layout/inc/pagestart2.jsp
language cannot be resolved to a variable
1: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2: <html lang="<%=language%>">
3: <%@ include file="/layout/inc/head.jsp"  %>
4: <%@ include file="/layout/inc/bodystart.jsp" %>
5: <%@ include file="/layout/inc/header.jsp" %>


    Stacktrace:
        org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:102)
        org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:331)
        org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:469)
        org.apache.jasper.compiler.Compiler.compile(Compiler.java:378)
        org.apache.jasper.compiler.Compiler.compile(Compiler.java:353)
        org.apache.jasper.compiler.Compiler.compile(Compiler.java:340)
        org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:646)
        org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357)
        org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
        org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

How do I modify pagestart.jsp so that it just defaults to ouputting

<html lang="en">

if the variable has not been setn


Solution

  • Just check if the variable exist and if it does then output what you need and if it doesn't output your default value.

    In your first JSP change the way you set your language:

    request.setAttribute("language", "en");
    

    So that in your second JSP you can access language as:

    String language = (String) request.getAttribute("language");
    <% if(language != null) {
        out.print("<html lang=\"" + language + "\">");
    } else {
        out.print("<html lang=\"en\">");
    }
    %>