Spring

spring ApplicationScope와 ServletContext의 개념과 예제

shika 2022. 1. 26. 23:50

ServletContext에 대해서 알아보자

먼저 간단히 개념을 알아보면

ServletContext객체에 데이터를 담으면 

서버가 종료될때 까지 사용할 수 있다(한마디로 서버끄기전까지 계속 유지됨)

이것이 바로 ApplicationScope의 범위이다.

 

ServletContext는 HttpServletRequest 객체로부터 추출이 가능하다

또한 Controller에서 주입 받을 수도 있다.

 

ServletContext는 어노테이션으로 Controller에서 주입시 파라메타에서는 받을 수 없다.

(이때는 어노테이션도 따로 사용안한다)

 

 

사용할 때는 이런식으로 @Autowired ServletContext를 이용해 사용한다.

ServletContext객체를 이용해야지 application영역에 저장을 할 수 있다.

	@Autowired
	ServletContext application;

그리고 @Autowired이후에

application.setAttribute(" ", ~) 나 application.getAttribute를 이용해서

ApplicationScope를 사용하는 것이다.

 

긴 코드로 살펴보자

@Controller
public class TestController {
	
	@Autowired
	ServletContext application;
	
	@GetMapping("/test1")
//	public String test1(HttpServletRequest request) {
	public String test1(){
		//ServletContext application = request.getServletContext();
		//서블릿컨텍스트에 저장을 해주면 브라우져에 상관없이 똑같은 메모리공간을 사용하게됨
		application.setAttribute("data1", "문자열1");
		
		DataBean1 bean1 = new DataBean1();
		bean1.setData1("data1");
		bean1.setData2("data2");
		application.setAttribute("bean1", bean1);
		return "test1";
	}

	@GetMapping("/result1")
//	public String result1(HttpServletRequest request) {
	public String result1() {
//		ServletContext application = request.getServletContext();
		String data1 = (String)application.getAttribute("data1");
		System.out.println("data1 : "+data1);
		
		DataBean1 bean1 = (DataBean1)application.getAttribute("bean1");
		System.out.println("bean1.data1 : "+bean1.getData1());
		System.out.println("bean1.data2 : "+bean1.getData2());
		return "result1";
	}
}

주석을 없애도 가능하고 위에 코드처럼 주석치고 사용하면

@Autowired ServletContext를 사용한 것이다.

 

jsp에서는 이런식으로 출력한다

<body>
	<h1>result1</h1>
	<h3>data1 : ${applicationScope.data1 }</h3>
	<%-- <h3>data1 : ${data1 }</h3> 이것도 가능 --%>
	<h3>bean1.data1 : ${applicationScope.bean1.data1 }</h3>
	<h3>bean1.data1 : ${applicationScope.bean1.data2 }</h3>
</body>

출력화면은 이렇게 된다.

콘솔은 이렇게

 

요약하자면 

ApplicationScope는 서버가 켜지고 꺼질때까지

한마디로 서버끄기전까지 계속 지속이 되는것이고 

보통 사용할때는

@Autowired

  ServletContext ~  이렇게

 

ServletContext를 활용해서 사용한다.

 

~.setAttribute 만 쓰면

바로 jsp에서 사용가능하다 ${}를 통해서

(따로ApplicationScope는 다른것과 다르게

model에 담거나 그런거 안해도 바로 화면에 출력 가능!!!)