How is JSP configuration performed in the deployment descriptor?
sobes.tech AI
Answer from AI
The JSP configuration in the deployment descriptor web.xml is done using <servlet> and <servlet-mapping> elements. The JSP file is processed as a special type of servlet.
-
Declaring JSP as a servlet:
The
<servlet>element is used to declare the resource (<servlet-class>points to the servlet implementation, but for JSP it is provided by the container) and assign it a logical name (<servlet-name>). In the case of JSP, the class name is not specified, and the<jsp-file>element is used.<!-- * Declaring a JSP file as a servlet --> <servlet> <servlet-name>myJspPage</servlet-name> <jsp-file>/myJsp.jsp</jsp-file> <!-- Path to the JSP file relative to the web application root --> <!-- * Optional initialization parameters for the JSP page --> <init-param> <param-name>paramName</param-name> <param-value>paramValue</param-value> </init-param> </servlet> -
Mapping URL pattern to the JSP servlet:
The
<servlet-mapping>element associates the servlet's logical name (<servlet-name>) with a URL pattern (<url-pattern>), through which this servlet (and consequently, the JSP) will be accessible.<!-- * Mapping a URL pattern to the declared JSP servlet --> <servlet-mapping> <servlet-name>myJspPage</servlet-name> <url-pattern>/mypage</url-pattern> <!-- URL where the JSP will be accessible --> </servlet-mapping> -
Other configurations:
You can also configure other aspects, such as:
<load-on-startup>: Defines the order of JSP loading (lower values load earlier).<security-constraint>: Applies security restrictions.<error-page>: Defines error pages.
Full configuration example:
<!--
* Deployment descriptor for the web application
-->
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--
* Defining a JSP file as a servlet "myJspPage"
-->
<servlet>
<servlet-name>myJspPage</servlet-name> <!-- Logical name of the servlet -->
<jsp-file>/myJsp.jsp</jsp-file> <!-- Path to the JSP file -->
<load-on-startup>1</load-on-startup> <!-- Load on startup -->
</servlet>
<!--
* Mapping URL pattern "/mypage" to the servlet "myJspPage"
-->
<servlet-mapping>
<servlet-name>myJspPage</servlet-name>
<url-pattern>/mypage</url-pattern> <!-- Accessible URL -->
</servlet-mapping>
<!--
* Example of another mapping for a different JSP
-->
<servlet-mapping>
<servlet-name>anotherJsp</servlet-name>
<url-pattern>/another</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>anotherJsp</servlet-name>
<jsp-file>/anotherPage.jsp</jsp-file>
</servlet>
</web-app>
Thus, web.xml manages how JSP files are transformed into servlets and which URLs invoke their execution, as well as configuring their initialization and loading behavior.