pageContext.setAttribute
, pageContext.getAttribute
forward
: request 객체의 setAttribute() 메소드로 값을 설정한 후, 서블릿이나 jsp에게 결과를 전달하여 값을 출력하도록 하는 것ApplicationScope01.java
package examples;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ApplicationScope01")
public class ApplicationScope01 extends HttpServlet {
private static final long serialVersionUID = 1L;
public ApplicationScope01() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
ServletContext application = getServletContext();
int value =1;
application.setAttribute("value", value);
out.println("<H1>value: "+value+"</H1>");
}
}
ApplicationScope02.java
package examples;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ApplicationScope02")
public class ApplicationScope02 extends HttpServlet {
private static final long serialVersionUID = 1L;
public ApplicationScope02() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
ServletContext application = getServletContext();
try { //만약 value를 불러왔을 때 ApplicationScope01.java에서 선언되지 않았다면 null값이 반환되므로 예외처리 해주기
int value = (int)application.getAttribute("value"); //Object로 반환되므로 int로 형변환해서 value에 저장
value ++;
application.setAttribute("value", value);
out.println("<H1>value: "+value+"</H1>");
} catch(NullPointerException e) {
out.println("value에 값이 없습니다");
}
}
}
ApplicationScope01.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
try{
int value = (int)application.getAttribute("value");
value ++;
application.setAttribute("value", value);
%>
<h1><%=value%></h1>
<%
}catch(NullPointerException e){
%> <h1>value값이 없습니다</h1>
<% }
%>
</body>
</html>
실습 결과