JSP内置对象-Application

1 JSP application内置对象

在JSP中,application是ServletContext类型的内置对象。

当应用程序或项目部署在服务器上时,ServletContext仅由Web容器创建一次。

该对象可用于从配置文件(web.xml)获取初始化参数。它也可以用于从应用程序范围中获取,设置或删除属性。

2 application内置对象的示例

2.1 编写index.jsp

<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<html>
<head>
    <meta charset="utf-8">
    <title>一点教程网-JSP application内置对象</title>
</head>
<body>
<form action="welcome">
    <input type="text" name="uname">
    <input type="submit" value="提交"><br/>
</form>
</body>
</html>

2.2 编写welcome.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>一点教程网-JSP application内置对象</title>
</head>
<body>

<%

    out.print("欢迎你 "+request.getParameter("uname"));

    String driver=application.getInitParameter("driver-name");
    out.print(" 驱动名称是="+driver);

%>

</body>
</html>

2.3 配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<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_3_1.xsd"
         version="3.1">

    <servlet>
        <servlet-name>yiidian</servlet-name>
        <jsp-file>/welcome.jsp</jsp-file>
    </servlet>

    <servlet-mapping>
        <servlet-name>yiidian</servlet-name>
        <url-pattern>/welcome</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>driver-name</param-name>
        <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
    </context-param>

</web-app>

2.4 运行测试

推荐好课