Spring/Spring MVC

Spring MVC - SessionScope 빈 주입

jddng 2021. 12. 29. 21:01
728x90
반응형

Session

  • 브라우저가 최초로 서버에 요청을 하게 되면 브라우저당 하나씩 메모리 공간을 서버에서 할당받는다.
  • 이 메모리 영역은 브라우저당 하나씩 지정되며 요청이 새롭게 발생하더라도 같은 메모리 공간(session)을 사용
  • 브라우저 종료할 때까지 Session에 저장된 데이터는 유지된다.

SessionScope

  • 브라우저가 최초의 요청을 발생 시키고 브라우저를 닫을 때까지의 범위를 뜻한다.
  • SessionScope에서는 Session 영역에 저장되어 있는 데이터나 객체를 자유롭게 사용할 수 있다.

방법 1 - Java, SessionScope으로 Bean 주입

 

RootAppContext.java 에서 정의한 bean 주입 

하나는 Bytypte으로 또 다른 하나는 Byname으로 쓰기 위해 두 개의 Bean들을 정의한다. 

// 프로젝트 작업시 사용할 bean을 정의하는 클래스
@Configuration
public class RootAppContext {

	@Bean
	@SessionScope
	public DataBean1 dataBean1() {
		return new DataBean1();
	}
	
	@Bean("sessionBean2")
	@SessionScope
	public DataBean2 dataBean2() {
		return new DataBean2();
	}
}

 

@Controller
public class testController {

	@Autowired
	DataBean1 sessionBean1;
	
	@Resource(name = "sessionBean2")
	DataBean2 sessionBean2;
	
	@GetMapping("/test1")
	public String test1() {
		
		sessionBean1.setData1("문자열1");
		sessionBean1.setData2("문자열2");
		sessionBean2.setData3("문자열3");
		sessionBean2.setData4("문자열4");
		
		return "test1";
	}
	@GetMapping("result1")
	public String result1(HttpSession model) {
		
		System.out.println(sessionBean1.getData1());
		System.out.println(sessionBean1.getData2());
		System.out.println(sessionBean2.getData3());
		System.out.println(sessionBean2.getData4());
		
		
		model.setAttribute("sessionBean1", sessionBean1);
		model.setAttribute("sessionBean2", sessionBean2);
		
		return "result1";
	}
}

 

@Autowired
DataBean1 sessionBean1;
 - RootContext.java 에서 정의한 Bean을 Bytype으로 주입한다.
 - SessionScope일 때 dataBeab1을 주입하고, Session 영역에는 자동으로 저장이 안된다.
  따라서 Model이나 HttpServletRequest, HttpSession를 통해 저장한다. 

@Resource(name = "sessionBean2")
DataBean2 sessionBean2;
 - RootContext.java 에서 정의한 Bean을 Byname으로 주입한다.
 - Byname으로 주입한 sessionBean2는 자동으로 request 영역에 저장된다.
 - SessionScope일 때 dataBeab2을 주입하고, Session 영역에는 자동으로 저장이 안된다.
  따라서 Model이나 HttpServletRequest, HttpSession를 통해 저장한다. 

// public String result1(Model model){
public String result1(HttpSession model) {
 - jsp에서 사용하기 위해 request 영역에 저장해도 되고, session 영역에 저장해도 된다.

 


 

@Component으로 정의한 bean 주입

 우선 @Component를 이용해 Bean을 정의한다.

@Component
@SessionScope
public class DataBean3 {
	private String data5;
	private String data6;
	
    //.... setter, getter
}
@Component(value = "sessionBean4")
@SessionScope
public class DataBean4 {

	private String data7;
	private String data8;
	
	// ..... setter, getter
}

 하나는 Bytype으로 가져오기 위해 이름을 정해주지 않았고, 다른 하나는 Byname으로 가져오기 위해 이름을 정해줬다. @Component로 정의한 Bean을 사용할 수 있도록 SevletAppContext.java 에 스캔 패키지를 지정해준다.

// Spring MVC 프로젝트에 관련된 설정을 하는 클래스
@Configuration
// Controller 어노테이션이 셋팅되어 있는 클래스를 Controller로 등록한다.
@EnableWebMvc
// 스캔할 패키지를 지정한다.
@ComponentScan("kr.co.controller")
@ComponentScan("kr.co.beans")
public class ServletAppContext implements WebMvcConfigurer{
	// Controller의 메서드가 반환하는 jsp의 이름 앞뒤에 경로와 확장자를 붙혀주도록 설정한다.
	@Override
	public void configureViewResolvers(ViewResolverRegistry registry) {
		....
	}
	
	// 정적 파일의 경로를 매핑한다.
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		....
	}
}
@ComponentScan("kr.co.beans")
 - @component 로 정의한 Bean들을 사용할 수 있도록 @Component를 찾기 위해 스캔해준다.

 

@Controller
public class testController {

	@Autowired
	DataBean3 sessionBean3;
	
	@Resource(name = "sessionBean4")
	DataBean4 sessionBean4;
	
	@GetMapping("/test1")
	public String test1() {

		sessionBean3.setData5("문자열5");
		sessionBean3.setData6("문자열6");
		sessionBean4.setData7("문자열7");
		sessionBean4.setData8("문자열8");
		
		return "test1";
	}
	@GetMapping("result1")
	public String result1(HttpSession model) {
		
		System.out.println(sessionBean3.getData5());
		System.out.println(sessionBean3.getData6());
		System.out.println(sessionBean4.getData7());
		System.out.println(sessionBean4.getData8());
		
		model.setAttribute("sessionBean3", sessionBean1);
		model.setAttribute("sessionBean4", sessionBean2);
		
		return "result1";
	}
}
@Autowired
DataBean3 sessionBean3;
 - @Component 로 정의한 Bean을 Bytype으로 주입
 - SessionScope일 때 dataBeab1을 주입하고, Session 영역에는 자동으로 저장이 안된다.
  따라서 Model이나 HttpServletRequest, HttpSession를 통해 저장한다. 

@Resource(name = "sessionBean4")
DataBean4 sessionBean4;
 - @Component 로 정의한 Bean을 Byname으로 주입
 - SessionScope일 때 dataBeab2을 주입하고, Session 영역에는 자동으로 저장이 안된다.
  따라서 Model이나 HttpServletRequest, HttpSession를 통해 저장한다. 

model.setAttribute("sessionBean1", sessionBean1);
model.setAttribute("sessionBean2", sessionBean2);
 - jsp에서 사용하기 위해서는 request 영역이나, session 영역에 저장해줘야 한다.
 - 여기에서는 session 영역에 저장해주었다.

 


 

방법 2 - xml, SessionScope으로 Bean 주입

 

root-context.xml 에서 정의한 bean 주입 

 하나는 Bytypte으로 또 다른 하나는 Byname으로 쓰기 위해 두 개의 Bean들을 정의한다. 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans
	   					   http://www.springframework.org/schema/beans/spring-beans.xsd">
	   <bean class='kr.co.beans.DataBean1' scope='session'/>
	   <bean class='kr.co.beans.DataBean2' id = 'sessionBean2' scope='session'/>		   
</beans>

 

@Controller
public class testController {

	@Autowired
	@Lazy
	DataBean1 sessionBean1;
	
	@Resource(name = "sessionBean2")
	@Lazy
	DataBean2 sessionBean2;

	@GetMapping("/test1")
	public String test1() {
		
		sessionBean1.setData1("문자열1");
		sessionBean1.setData2("문자열2");
		
		sessionBean2.setData3("문자열3");
		sessionBean2.setData4("문자열4");
				
		return "test1";
	}
	@GetMapping("result1")
	public String result1(Model model) {
		
		System.out.println(sessionBean1.getData1());
		System.out.println(sessionBean1.getData2());
		
		System.out.println(sessionBean2.getData3());
		System.out.println(sessionBean2.getData4());
		
		model.addAttribute("sessionBean1", sessionBean1);
//		이름을 정의한 sessionBean1은 자동으로 session 영역에 저장되어 
//		request에 저장된다.
		
		return "result1";
	}
}
@Autowired
@Lazy
DataBean1 sessionBean1;
 - root-context.xml 에서 정의한 Bean을 Bytype으로 주입
 - @Lazy를 넣어주는 이유는 서버가 가동되면 서버에서는 자동으로 root-context.xml에 정의한
  Bean들을Autowired된 곳에 주입하려고 한다. 하지만 아직 클라이언트로부터 요청이 오지 않았기
  때문에 주입이 되지않는 상황이 발생하여 에러가 나기 때문에 @Lazy를 넣어준다.

@Resource(name = "sessionBean2")
@Lazy
DataBean2 sessionBean2;
 - root-context.xml 에서 정의한 Bean을 Byname으로 주입

model.addAttribute("sessionBean1", sessionBean1);
 - jsp에서 사용하기 위해 request영역에 저장했다.
 - sessionBean2는 Byname으로 주입하였기때문에 자동으로 request영역에 저장이 된다.

 

@Component으로 정의한 bean 주입

 우선 @Component를 이용해 방법 1과 같이 Bean을 정의해준다.(생략하겠다). Bean을 정의해주면

@Component로 정의한 Bean을 사용 할 수 있도록 sevlet-context.xml에 스캔 패키지를 지정해준다.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
			 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
			 xmlns:beans="http://www.springframework.org/schema/beans"
			 xmlns:context="http://www.springframework.org/schema/context"
			 xsi:schemaLocation="http://www.springframework.org/schema/mvc
			 		     http://www.springframework.org/schema/mvc/spring-mvc.xsd
			 		     http://www.springframework.org/schema/beans
			 		     http://www.springframework.org/schema/beans/spring-beans.xsd
			 		     http://www.springframework.org/schema/context
			 		     http://www.springframework.org/schema/context/spring-context.xsd">
			 					 
	<!-- 스캔한 패지키 내부의 클래스 중 Controller 어노테이션을 가지고 있는 클래스들을 Controller로 로딩하도록 한다 -->
	<annotation-driven/>
	
	<!-- 스캔할 bean들이 모여있는 패키지를 지정한다. -->
	<context:component-scan base-package="kr.co.controller"/>
	<context:component-scan base-package="kr.co.beans"/>
	
	<!-- Controller의 메서드에서 반환하는 문자열 앞 뒤에 붙힐 경로 정보를 셋팅한다. -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/"/>
		<beans:property name="suffix" value=".jsp"/>
	</beans:bean>
	
	<!-- 정적파일(이미지, 사운드, 동영상, JS, CSS 등등) 경로 셋팅 -->
	<resources mapping="/**" location="/resources/"/>
	
</beans:beans>
<context:component-scan base-package="kr.co.softcampus.beans"/>
 - @Component 로 정의한 Bean들을 사용 할 수 있도록 해당 패키지를 스캔해준다.
@Controller
public class testController {

	@Autowired
	DataBean3 sessionBean3;
	
	@Resource(name = "sessionBean4")
	DataBean4 sessionBean4;
	
	@GetMapping("/test1")
	public String test1() {

		sessionBean3.setData5("문자열1");
		sessionBean3.setData6("문자열2");
		
		sessionBean4.setData7("문자열3");
		sessionBean4.setData8("문자열4");
		
		return "test1";
	}
	@GetMapping("result1")
	public String result1(Model model) {
		
		System.out.println(sessionBean3.getData5());
		System.out.println(sessionBean3.getData6());
		
		System.out.println(sessionBean4.getData7());
		System.out.println(sessionBean4.getData8());
		
		model.addAttribute("sessionBean3", sessionBean1);
		model.addAttribute("sessionBean4", sessionBean1);
		
		return "result1";
	}
}
@Autowired
DataBean3 sessionBean3;
 - @Component로 정의한 Bean 을 Bytype으로 주입
 - @Component로 정의한 Bean 은 @Lazy를 사용 안해도 된다.

@Resource(name = "sessionBean4")
DataBean4 sessionBean4;
 - @Component로 정의한 Bean 을 Byname으로 주입

model.addAttribute("sessionBean3", sessionBean1);
model.addAttribute("sessionBean4", sessionBean1);
 - @Component 로 주입한 Bean은 Byname으로 주입하였더라도 자동으로 request 영역에 저장이 안 된다.
 - 따라서, request 영역에 저장해 주었다. (session 영역에 저장해도 됨)
728x90
반응형