Servelt Context의 이해와 사용 장면

최근에 프로젝트를 하면서 익숙하지 않은 것을 썼지만 나 자신은 또 매우 유용하다고 느꼈다.그러니까 기록해..
 
1. ServletContext 사용
ServletContext 객체는 웹 응용 프로그램을 마운트할 때 초기화되며 서버가 시작되고 서버가 종료되는 주기입니다.즉, 웹 응용 프로그램이 시작 상태라면 계속 살아남는 것이다.웹 프로그램을 닫을 때, 웹 프로그램도 회수됩니다.
ServletContext 객체의 setAttribute 및 getAttribute에 대한 기본 사용법:
ServletContext는 HttpServletRequest, HttpSession과 같이 하나의 맵 구조로 사용할 수 있습니다.차이는 그들 사이의 작용 범위와 생명 주기가 다르다는 데 있다.
프로그램이 어떤 종류에서 한 번만 실행되기를 원하면, 그 다음에는 실행하지 않습니다.웹 환경에서 여러 번 호출될 수 있는 클래스는 왕왕 액션이나 정시 작업 스케줄링 클래스이다.액션이나 정시 작업 스케줄링 클래스가 몇 번 호출되었든 코드가 한 번만 실행되기를 원할 때 ServletContext로 표시할 수 있습니다.스케줄링 클래스가 있는 경우 TestTrigger (정시 작업 구성 약관):
 
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
		ServletContext servletContext =  webApplicationContext.getServletContext();
		String count = (String) servletContext.getAttribute("count");
		if (StringUtils.equals("1", count)){ //  
			System.out.println(sdf.format(new Date()) + ": TestTrigger 1 。。");
		}else{
			servletContext.setAttribute("count", "1");
			System.out.println(sdf.format(new Date()) + ": TestTrigger 。。。");
		}
또 하나의 액션:
 
 
@RequestMapping("/test/context.json")
	@ResponseBody
	public void test() {
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
		ServletContext servletContext =  webApplicationContext.getServletContext();
		String count = (String) servletContext.getAttribute("count");
		if (StringUtils.equals("1",count)){ //  
			System.out.println(sdf.format(new Date()) + ": TestAction 1 。。");
		}else{
			servletContext.setAttribute("count", "1");
			System.out.println(sdf.format(new Date()) + ": TestAction 。。。");
		}
	}
웹 프로젝트를 시작하면,
[먼저] 브라우저에 주소를 입력합니다.http://localhost:8080/프로젝트 이름/
test/context.json
타이밍 퀘스트 스케줄링 클래스 TestTrigger【후】가 촉발,
콘솔에서 다음 결과가 출력됩니다.
 
14:22:27: Test Action 첫 번째 실행...
14:23:00: TestTrigger는 첫 번째 실행이 아닙니다.
이상의 출력 결과에 의하면 ServletContext의 작용 범위는 전체 웹 프로젝트입니다. Test Action을 다시 호출할 때, 정시 작업이 다시 스케줄링될 때입니다.인쇄 결과는 다음과 같습니다.
14:24:00: TestTrigger는 첫 번째 실행이 아닙니다.
14:24:30: TestAction은 첫 번째 수행이 아닙니다.
이것은 우리가 테스트를 통해 어떤 코드가 전체 웹 프로젝트에서 한 번만 실행되는 효과에 도달할 수 있다는 것을 설명한다.마찬가지로 제어를 통해 시간 작업 클래스를 먼저 스케줄링하고 이 Action에 접근합니다.첫 인쇄 결과는 상반될 것이다.
물론 이상은 ServletContext의 역할 범위를 테스트하는 테스트일 뿐입니다.실제 개발에서 모든 Action이나 정시 작업 스케줄링 클래스는 자신의 setAttribute 동작을 가지고 있을 것이다.모든 Action이나 정시 작업 스케줄링 클래스에는 [한 번만] 의 코드 논리가 있을 수 있기 때문이다.
예를 들어 상기 테스트에서 TestTrigger는 setAttribute("testTriigger", "1")를 할 수 있고 TestAttribute("testAction", "1")를 할 수 있다.이렇게 하면 그들이 스케줄링되거나 몇 번을 방문하든지 간에 한 번만 실행하는 코드 세션은 매번 실행하지 않아도 성능상의 병목을 초래할 수 있다.
Action 또는 정시 작업 스케줄링 클래스의 (1)static 정적 코드 블록
코드
(2)staticfinal 속성의 정의는 웹 용기가 초기화될 때 한 번 실행하고 실행하지만 현실에서는 추천하지 않는다.
그리고 주의해야 할 것은 다음과 같다.
1) 웹 프로젝트에서 당신이 통과하든
ContextLoader.getCurrentWebApplicationContext();메서드 생성 횟수
WebApplicationContext, 항상 같은 것을 얻을 수 있습니다
WebApplicationContext 객체;네가 통과하든지 말든지
webApplicationContext.getServletContext();생성 횟수
ServletContext, 항상 동일하게 제공
ServletContext 객체입니다.이것은 ServletContext의 라이프 사이클과 역할 범위와 관련이 있습니다.
2) setAttribute("test", "first")
setAttribute("test","second").두 번째 setAttribute 작업에 덮어쓰기 때문에 getAttribute("test")에서 얻을 수 있는 것은 second입니다.
소결:
1) ServletContext의 라이프 사이클 및 역할 범위입니다.
2) 어떤 코드가 클래스에 접근하거나 N번을 스케줄링하든지 간에 이 코드를 1회만 실행할 때 제어해야 한다.서로 다른 스케줄링 클래스에서 하나의 변수를 공동으로 사용해야 할 때 ServletContext를 사용해 보세요.

좋은 웹페이지 즐겨찾기