liguofeng29’s blog

個人勉強用ブログだっす。

JSP - applicationオブジェクト

applicationオブジェクトはwebアプリそのものを表している。

 
用途
1. JSP,servletの間で情報を共有できる。
2. webアプリの設定情報にアクセスできる。
 
put-application.jsp
<%@ page contentType="text/html;charset=Shift_jis" language="java" %>
<html>
<head>
<title>set attribute to application</title>
</head>
<body>
<%-- i宣言 --%>
<%!int i = 0;%>
<%-- applicationオブジェクトに属性設定 --%>
<%application.setAttribute("count", String.valueOf(i++));%>
<%-- i出力 --%>
i = <%=i%>
</body>
</html>

 

get-application.jsp
<%@ page contentType="text/html;charset=Shift_jis" language="java" %>
<html>
<head>
<title>get attribute to application</title>
</head>
<body>
<%-- applicationオブジェクトのcount属性取得 --%>
count = <%=application.getAttribute("count")%>
</body>
</html>

 

 

2. webアプリの初期化パラメータ取得

 
web.xml
<?xml version="1.0" encoding="UTF-8"?>
  <display-name>webDemo</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  <context-param>
    <param-name>URL</param-name>
    <param-value>http://host.com
  </context-param>
 
  <context-param>
    <param-name>user</param-name>
    <param-value>user1</param-value>
  </context-param>
 
  <context-param>
    <param-name>password</param-name>
    <param-value>password1</param-value>
  </context-param>
</web-app>
 

 

context-param-application.jsp
<%@ page contentType="text/html;charset=Shift_jis" language="java" %>
<html>
<head>
<title>get context paramert</title>
</head>
<body>
 
<%-- web.xmlのcontext-paramを取得する --%>
URL = <%=application.getInitParameter("URL")%><br>
user = <%=application.getInitParameter("user")%><br>
password = <%=application.getInitParameter("password")%><br>
 
<!-- 存在しない際にはNULL -->
存在しない際にはNULL = <%=application.getInitParameter("XXXXX")%><br>
 
</body>
</html>