How do you pass an InitParameter to a JSP?
Created May 4, 2012
Sameer Tyagi The JspPage interface defines the jspInit() and jspDestroy() method which the page writer can
use in their pages and are invoked in much the same manner as the init() and destory() methods
of a servlet.
The example page below enumerates through all the parameters and prints them to the console.
---------------------------------------------------------------------------- <%@ page import="java.util.*" %> <%! ServletConfig cfg =null; public void jspInit(){ ServletConfig cfg=getServletConfig(); for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();) { String name=(String)e.nextElement(); String value = cfg.getInitParameter(name); System.out.println(name+"="+value); } } %>
<html> <body> <h1> See the console for the init params accessible by this JSP page </h1> </body> </html> ----------------------------------------------------------------------------The second part, where are these parameters defined ? The engine translates the JSP into source and uses a base servlet class that it extends. This base servlet class is engine dependant and so is the configuration.In other words, where these are defined depends on the engine that you are using. In the JSWDK 2 parameters,myparam1 and myparam2 for the JSP above are defined in the Web-inf/servlet.properties file
---------------------------------------------------------------------------- # $Id: servlets.properties,v 1.3.2.2 1999/07/27 00:52:13 mandar Exp $ # Define servlets here # <servletname>.code=<servletclass> # <servletname>.initparams=<name=value>,<name=value> #snoop.code=SnoopServlet #snoop.initparams=initarg1=foo,initarg2=bar cookie.code=CookieExample cookie.initparams=foo jsp.code=com.sun.jsp.runtime.JspServlet jsp.initparams=keepgenerated=true,myparam1=val1,myparam2=val2 jts.code=servletToJsp jts.initparams=foo ----------------------------------------------------------------------------Couple of points,init parameters defined will be available to all JSPs since they are bound to the same servlet ,unique names should be used across different JSPs. The whole approach should actually be avoided, because if the JSP depends on initiaization then chances are it should actually be coded as a servlet or the code needs to be moved to a bean. JSPs strive to seperate code from presentation, too much code in the JSP usually contradicts this.