Java.Serlet.How to configure initialization parameters for JSP?

Initialization parameters are name–value pairs that are passed to the JSP/servlet when the server loads it.

There are two ways to configure them:


🔵 1. Using web.xml (Traditional way)

You can define JSP initialization parameters inside the web.xml file of your application.

Example in WEB-INF/web.xml:

<jsp-config>
    <jsp-property-group>
        <url-pattern>/myPage.jsp</url-pattern>
        <init-param>
            <param-name>siteName</param-name>
            <param-value>My Cool Website</param-value>
        </init-param>
        <init-param>
            <param-name>adminEmail</param-name>
            <param-value>admin@example.com</param-value>
        </init-param>
    </jsp-property-group>
</jsp-config>

✅ This means when myPage.jsp is accessed, these initialization parameters are available.

🔵 2. Using Servlet-style Configuration (if JSP mapped as a servlet)

You can configure a JSP like a servlet if you map it inside web.xml.

Example:

<servlet>
    <servlet-name>myPage</servlet-name>
    <jsp-file>/myPage.jsp</jsp-file>
    <init-param>
        <param-name>theme</param-name>
        <param-value>dark</param-value>
    </init-param>
</servlet>

<servlet-mapping>
    <servlet-name>myPage</servlet-name>
    <url-pattern>/customPage</url-pattern>
</servlet-mapping>

✅ Here, /customPage maps to myPage.jsp, and it will have a theme=dark init parameter.

🛠️ How to Access Initialization Parameters in the JSP?

Inside your JSP, you can use the config implicit object (which is a ServletConfig).

Example in JSP:

<%
    String siteName = config.getInitParameter("siteName");
    String adminEmail = config.getInitParameter("adminEmail");
%>

<h1>Welcome to <%= siteName %>!</h1>
<p>Contact us at: <%= adminEmail %></p>

config.getInitParameter("param-name") fetches the value.

🎯 Final Summary

StepAction
DefineAdd <init-param> entries in web.xml under <jsp-config> or <servlet>
AccessUse config.getInitParameter("param-name") inside JSP
UsageGreat for passing fixed settings without hardcoding them into JSP code

📢 Extra Tip:

  • Initialization parameters are read-only: you can read them but cannot change them inside the JSP.
  • They are mainly used for configuration — not for dynamic per-user data.
This entry was posted in Без рубрики. Bookmark the permalink.