프레임워크 = 틀
수많은 기능들을 추상화 시켜놓고 대기시켜놓는다. 틀 안에서 주요 업무를 작성하는 것
DI, AOP, MVC, JDBC를 제공한다
스프링 프레임워크의 모듈
하나하나의 틀 = 모듈
spring - core : 스프링의 핵심인 DI와 IoC를 제공
spring - aop : AOP구현 기능 제공(관점 지향 프로그래밍)
spring - jdbc : 데이터베이스를 설계
spring - tx : 스프링에서 제공하는 트랜젝션 관련 기능 제공
spring-webmvc : 스프링에서 제공하는 컨트롤러 뷰를 이용한 스프링 MVC 구현 기능 제공
웹 어플리케이션을 프로그래밍하려면,
스프링 코어 + jdbc + webmvc를 사용한다.
제공되어진 라이브러리를 사용해서 기능 구현을 해나가면 된다.
원래 라이브러리를 다운 받아서 임포트해서 사용
근데 이제는 개발하고 있는 프로젝트의 환경설정 파일 (xml파일)등을 이용해서 라이브러리르 자동으로 다운 받는다
기능들은 다 모듈화되어있다!!!
스프링 컨테이너
스프링에서 객체를 생성하고 조립하는 컨테이너로
컨테이너를 통해 생성된 객체를 빈이라고 부른다.
자바 기반으로 만들어짐
xml문서를 이용해서 객체 생성 및 속성, 데이터 작성
스프링 컨테이너 : xml문서를 이용해서 만들어진 객체들을 담고 있는 큰 그릇 → Bean이라 그런다.
컨테이너 안에 여러 가지 객체를 담고 있다.
스프링 컨테이너에 있는 거를 필요할 때마다 꺼내서 사용하면 된다.
메인 클래스라는 큰 틀 안에
My calculator 안에 외부 객체를 생성자에 집어넣은거다.
MyCalculator → 컨테이너다
필요한 객체들을 외부에다가 만들어놓고 외부에서 주입해준다.
개발환경구축
JVM < API < JRE < JDK
스프링 프로젝트 생성
Maven : 스프링 프로젝트 빌드하는 툴
group id : 프로젝트를 감싸는 큰 프로젝트가 있을 수 있다. 그 큰 프로젝트의 id
artifact id : 각 프로젝트를 의미하는 아이디
spring → 모듈로 구성된다.
그럴 때 각 모듈 하나하나도 프로젝트다. 각 모듈 하나는 artifact id. 스프링의 버전은 group id 가 될 수 있다.
설정할게 몇 가지가 있다.
pom.xml : 스프링을 사용하기 위해서는 모듈을 사용하게 된다.
필요한 모듈을 가져오기 위한 파일이 바로 pom.xml
java 폴더→ 기능 구현
resources 폴더 → 보조적인 파일들
pom.xml 파일은 메이븐 설정파일로 메이븐은 라이브러리를 연결해주고, 빌드를 위한 플랫폼이다.
pom.xml → dependencies 태그 , build 태그
applicationContext.xml : bean을 만들어주는 파일, 객체를 컨테이너 안에 담아둔다.
applicationContext라는 파일의 태그에 의해서 자동으로 객체가 생성된다. new를 사용하지 않아도 된다.
package testPjt;
import org.springframework.context.support.GenericXmlApplicationContext;
public class MainClass{
public static void main(String[]args){
//TranspotationWalk transpotationWalk = new TranspotationWalk();
//transpotationWalk.move();
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationContext.xml");
TranspotationWalk transpotationWalk = ctx.getBean("tWalk",TranspotationWalk.class);
transpotationWalk.move();
ctx.close();
}
}
Java
복사
DI
스프링 컨테이너 : 객체들을 모아놓은 큰 공간
Dependency Injection : 의존성 주입
배터리 일체형 : 배터리가 떨어지면 장난감을 새로 구입해야한다.
배터리 분리형 : 배터리가 떨어지면 배터리만 교체하면 된다.
객체가 전체 프로젝트에 구속되어있으면, 기능을 추가할 때 프로젝트를 다시 만들어 줘야한다.
객체가 전체 프로젝트에 상관없이 독립화 되어있으면, 필요에 따라서 객체를 사용한다.
배터리란 객체에 의존해서 완벽한 장난감이 만들어지는 것. 배터리에 의존한다. 배터리를 주입해서 의존성을 만드는 것 → 의존성 주입
public class ElectronicRadioToy {
private Battery battery
public ElectronicRadioToy(Battery battery ){
this.battery = battery
}
public void setBattery(Battery battery ){
this.battery = battery
}
}
Java
복사
객체를 만들어서 외부에서 주입하는 방법 : 의존 주입이라고한다.
컨테이너 안에서 객체끼리 얽혀있다.
객체 안에 객체가 있는 것들 ⇒ 의존성 주입이 된 것들이다.
객체를 주입하는 방식: set함수를 이용하자
public StudentRegisterService(StudentDao studentDao ){
this.studentDao = studentDao;
}
public StudentModifyService(StudentDao studentDao ){
this.studentDao = studentDao;
}
public StudentDeleteService(StudentDao studentDao ){
this.studentDao = studentDao
}
public StudentSelectService(StudentDao studentDao ){
this.studentDao = studentDao
}
public StudentAllSelectService(StudentDao studentDao ){
this.studentDao = studentDao
}
Java
복사
<bean id =="studentDao" class =="ems.member.dao.StudentDao" ></bean>
<bean id =="registerService" class =="ems.member.service">
<constructor arg ref =="studentDao"></constructor arg>
</bean>
<bean id =="modifyService" class =="ems.member.service.>
<constructor arg ref =="studentDao" </constructor arg>
</bean>
Java
복사
다양한 의존 객체 주입
1.
생성자를 이용한 의존 객체 주입
2.
setter를 이용한 의존 객체 주입
public void setJdbcUrl(String jdbcUrl) {
this.jdbcUrl = jdbcUrl;
}
public void setUserId(String userId) {
this.userId = userId;
}
public void setUserPw(String userPw) {
this.userPw = userPw;
}
Java
복사
<bean id="dataBaseConnectionInfoDev" class="ems.member.DataBaseConnectionInfo">
<property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:xe" />
<property name="userId" value="scott" />
<property name="userPw" value="tiger" />
</bean>
Java
복사
3.
List 타입 의존 객체 주입
public void setDevelopers(List<String> developers) {
this.developers = developers;
}
Java
복사
<property name="developers">
<list>
<value>Cheney.</value>
<value>Eloy.</value>
<value>Jasper.</value>
<value>Dillon.</value>
<value>Kian.</value>
</list>
</property>
Java
복사
4.
Map 타입 객체 주입
public void setAdministrators(Map<String, String> administrators) {
this.administrators = administrators;
}
Java
복사
<property name="administrators">
<map>
<entry>
<key>
<value>Cheney</value>
</key>
<value>cheney@springPjt.org</value>
</entry>
<entry>
<key>
<value>Jasper</value>
</key>
<value>jasper@springPjt.org</value>
</entry>
</map>
</property>
Java
복사
스프링 설정 파일 분리
스프링 설정 파일에서 모든 객체를 다 만들기 때문에, 많이 길어질 수 있다.
많은 코드가 하나의 xml파일에 담겨질 수 있다.
applicationContext.xml → appCtx1.xml, appCtx2.xml , appCtx3.xml
기능별로 구분을 많이 한다.
appctxs = {"classpath:appCtx1.xml", "classpath:appCtx2.xml", "classpath:appCtx3.xml"};
GenericApplicationContext ctx = new GenericApplicationContext(appctxs);
Java
복사
xml파일에서도 import할 수 있다.
<import resource = "classpath:appCtx2.xml">
컨테이너에서 bean을 get할 때 두 객체는 같은 객체이다. 동일한 객체를 참조한다.
싱글톤
스프링컨테이너에서 생성된 빈 ( 객체의 경우 동일한 타입에 대해서는 기본적으로 한 개만 생성이 되며 , getBean() 메소드로 호출될 때 동일한 객체가 반환 된다.
프로토타입
싱글톤 범위와 반대의 개념도 있는데 이를 프로토타입 (Prototype) 범위라고 한다 .
프로토타입의 경우 개발자는 별도로 설정을 해줘야 하는데 , 스프링 설정 파일에서 빈 객체을 정의할 때 scope 속성을 명시해 주면 된다
<bean id =="dependencyBean" class =="scope.ex.DependencyBean" scope ==" prototype">
<constructor arg ref ="injectionBean"/>
<property name ="injectionBean" ref ="injectionBean"/>
</bean>
Java
복사
의존 객체 자동 주입
자동으로 객체 간의 의존 관계를 설정해서 자동으로 주입하는 방법
객체를 주입할 때 <constructor-org> 또는 <property>태그로 의존 대상 객체를 명시하지 않아도 스프링 컨테이너가 자동으로 필요한 의존 대상 객체를 찾아서 의존 대상 객체가 필요한 객체에 주입해주는 기능이다.
구현 방법 : @Autowired , @Resource
@Autowired
주입하려고 하는 객체의 타입이 일치하는 객체를 자동으로 주입한다.
이름은 상관이 없고, 객체의 타입을 일치하는 것을 찾아서 자동으로 집어넣는 것
컨스트럭터를 짤 때 @Autowired 를 붙인다.
그리고 xml파일에는 <context:annotation-config/>
<?xml version="1.0" encoding="UTF-8"?>
//추가되는 부분//
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config />
//////
<bean id="wordDao" class="com.word.dao.WordDao" >
<!-- <qualifier value="usedDao"/> -->
</bean>
<bean id="wordDao2" class="com.word.dao.WordDao" />
<bean id="wordDao3" class="com.word.dao.WordDao" />
<bean id="registerService" class="com.word.service.WordRegisterServiceUseAutowired" />
<bean id="searchService" class="com.word.service.WordSearchServiceUseAutowired" />
</beans>
Java
복사
생성자 이외의 프로퍼티나 메소드에도 넣어줄 수 있다. Autowired
생성자는 그냥 쓰면 되는데, 프로퍼티나 메소드에 쓰고 싶으면 디폴트 생성자를 하나 꼭 만들어줘야한다.
@Resource
객체의 이름을 본다
주입하려고 하는 객체의 이름이 일치 하는 객체를 자동으로 주입한다.
xml파일에서 id값을 찾는다.
생성자에는 쓰지 못하고, 프로퍼티나 메소드에 쓸 수 있다.
의존객체 선택
다수의 빈 ( 객체 중 의존 객체의 대상이 되는 객체를 선택하는 방법에 대해서 학습합니다
동일한 객체가 2 개 이상인 경우 스프링 컨테이너는
자동주입 대상 객체를 판단하지 못해서 Exception 을 발생시킨다.
qualifier 태그를 사용한다.
@Autowired(required = false)
: 의존객체 자동 주입 체크 속성, required = false → 의존객체가 있으면 넣고 없으면 넣지 마라는 뜻이다.
@inject
inject 어노테이션을 이용해서 넣을 수 있다.
@Autowired 와 차이점 이라면 @Autowired 의 경우 required 속성을 이용해서 의존 대상 객체가 없어도 익셉션을 피할 수 있지만, @Inject 의 경우 required 속성을 지원하지 않는다.
@Named 라는 걸로 exception을 피할 수 있다.
@Named(value = "빈 객체의 id")
생명주기
1.
스프링 컨테이너 생명주기
생성: GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:appCtx.xml");
스프링 컨테이너와 빈 객체의 생성 시점은 동일하다.
객체들을 불러와서 쓰고 나서는 close한다(소멸)
ctx.close();
2.
빈 객체 생명주기
생성되는 시점과 종료되는 시점에 뭔가를 하고 싶다!
→ afterPropertiesSet(), destroy() 메소드를 구현 with 인터페이스
3.
init-method, destroy-method 속성
<bean></bean>
안에다가 init-method = "initMethod" destroy-method = "destroyMethod" 속성을 넣는다
이 때 속성의 값과 같은 이름의 함수를 객체에서 구현하면 된다.
어노테이션을 이용한 스프링 설정
XML파일을 Java파일로 변경하기
XML을 이용한 스프링 설정파일 제작을 어노테이션을 이용해서 Java파일로 제작할 수 있는 방법에 대해 학습
import org.springframework.context.annotation.Configuration;
@Configuration
public class MemberConfig(){
//<bean id = "studentDao" class = "ems.member.dao.StudntDao"/>
@bean
public StudentDao studentDao(){
return new StudentDao();
}
/*
<bean id = "registerService" class = "ems.member.service.StudentRegisterSerivce">
<constructor-arg ref = "studentDao"></constructor-arg>
</bean>
*/
@bean
public StudentRegisterService registerService(){
return new StudentRegisterService(studentDao());
}
@bean
public StudentDeleteService deleteService(){
return new StudentDeleteService(studentDao());
}
@bean
public StudentModifyService modifyService(){
return new StudentModifyService(studentDao());
}
@bean
public StudentSelectService selectService(){
return new StudentSelectService(studentDao());
}
@bean
public DataBaseConnectionInfo dataBaseConnectionInfoDev(){
DataBaseConnectionInfo InfoDev = new DataBaseConnectionInfo();
infoDev.setJdbcUrl("jdbc:oracle:thin:@localhost:1521:xe");
infoDev.setUserId("scott");
infoDev.setUserPw("tiger");
return infoDev;
}
@bean
public DataBaseConnectionInfo dataBaseConnectionInfoReal(){
DataBaseConnectionInfo InfoReal = new DataBaseConnectionInfo();
infoReal.setJdbcUrl("dbc:oracle:thin:@192.168.0.1:1521:xe");
infoReal.setUserId("masterid");
infoReal.setUserPw("masterpw");
return infoReal;
}
//<list>태그는 ArrayList<String>이런 식으로 ArrayList데이터 타입을 사용하자
//<map>태그는 MAP<String, String> administrators = new HashMap();
//이런 식으로 Map을 사용하자.
}
Java
복사
이렇게 만든 자바 환경설정 파일을 사용할 때는
AnnotationConfigApplicationContext 객체를 사용한다.
AnnotationConfigApplicationContext = new AnnotationConfigApplicationContext(MemberConfig.class);
2. 자바 파일 분리
기능별로 분리한다.
DAO와 관련된 파일
DB연결과 관련된 파일
서비스와 관련된 파일
다른 파일에서 다른 파일의 메소드를 참조하려면 @Autowired를 이용하자!
컨테이너 생성할 때는 배열 형태로 그냥 집어넣으면 된다.
3. @import 어노테이션
@import({MemberConfig2.class, MemberConfig3.class})
웹 프로그래밍 설계 모델
스프링 MVC 프레임워크 기반의 웹 프로그래밍 구조에 대해서 학습합니다.
1.
웹 프로그래밍 구축하기 위한 설계 모델
모델1
브라우저
WAS(웹 어플리케이션 서버)
데이터베이스
JSP, Service & DAO
html 안에 자바 코드도 들어가고 각종 태그들이 들어간다.
html안에 자바를 짬뽕해서 넣기 때문에 개발속도가 빠르다.
여러 가지 언어를 짬뽕하다보니까, 유지보수하기가 굉장히 힘들다.
모델2
브라우저
WAS(Controller
Service
DAO )
Model
데이터베이스
Controller
View(JSP로 작성)
브라우저
2.
스프링 MVC 프레임워크 설계 구조
브라우저 →(요청) → DispatcherServlet
DispatcherServlet→ HandlerMapping (알맞은 컨트롤러를 선택한다)
DispatcherServlet
HandlerAdapter (요청한 데이터에 대해서 가장 적합한 메소드를 처리해준다, 모델이라는 데이터를 가져온다. 요청 처리 → Controller)
DispatcherServlet
ViewResolver(처리 결과를 출력할 View 선택)
DispatcherServlet → View(응답 생성)
View → 브라우저
3.
DispatcherServlet 설정
web.xml에 서블릿을 매핑 (JSP, Servlet 공부!!)
서블릿을 등록한다.
DispatcherServlet은 스프링 프레임워크 안에 있는 것이다.
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value> // 스프링 컨테이너를 만든다
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
XML
복사
초기 설정 파일로 스프링 설정파일을 이용한다.
만약에 설정하지 않으면 appServlet-context.xml을 찾는다
여기서 이제 HandlerMapping HandlerAdapter, ViewResolver 와 같은 빈 객체를 생성하는 컨테이너를 만든다.
4.
컨트롤러 객체 - @Controller
HandlerMapping, HandlerAdapter들은 만들어진다.
컨트롤러는 일반적인 클래스 파일로 만드는데 어노테이션을 Controller로 만든다.
@Controller
이럴려면 스프링 설정파일에 <annotation-driven/>이라는 태그를 넣어줘야한다.
5.
컨트롤러 객체 - @RequestMapping
컨트롤러 안에 있는 메소드에다가 @RequestMapping("/success")이라는 어노테이션을 붙인다.
이러면 url로 들어온 요청을 수행.
6.
컨트롤러 객체 - Model타입의 파라미터
Controller 뒤에는 Service, DAO, DB 등등이 있다.
작업을 다한 뒤에 올리는 데이터타입 = Model
모델 객체에 데이터를 담아서 DispatcherServlet에 전달할 수 있다.
이 모델 데이터는 View에서 가공되어 클라이언트에 응답처리 됨.
7.
View 객체
InternalResourceViewResolver라는 빈 객체를 하나 만든다.
컨트롤러의 return 값 + suffic + prefix 값으로 만들어진 파일을 응답.
8.
전체적인 웹 프로그래밍 구조
MVC 웹서비스
java파일: java파일들이 위치, Controller, Service, DAO 객체들 존재
webapp: 웹과 관련된 파일등이 위치
resources: html,css,js파일 등이 위치
spring: 스프링 컨테이너를 생성하기 위한 스프링 설정파일
views: view로 사용될 jsp파일 위치
pom.xml: 메인 레포에서 프로젝트에 필요한 라이브러리를 내려받기 위한 메이븐 설정
web.xml : 맨 처음에 웹이 읽을 때 읽어들이는 파일
ServletContext 파일을 설정해주고 있다. → DispatcherServlet으로 사용
ServletContext파일 → Web Resolver로 설정
HandlerMapping → 적합한 컨트롤러를 검색하는 것
HandlerAdapter → 적합한 메소드를 검색하는 것
Controller → 서비스, DAO, DB를 거쳐서 데이터를 처리
모델로 데이터를 주고 받는다.
Service & Dao 객체 구현
로그인 기능
Member객체 → 기본적인 로그인 기능을 위해 사용자들의 정보를 담는 객체
HomeControler → 맨 처음에 url을 받았을 때 띄워주는 창
webapp/resources : 프론트엔드 파일들이 존재
프론트엔드 파일들은 a태그를 통해 url을 연결하고 정보를 전달한다.
이렇게 연결된 url들을 컨트롤러를 통해 처리
컨트롤러 → url에 해당하는 서비스를 매핑해준다. 데이터를 모두 처리하고 나면 모델 객체를 통해 데이터와 view파일을 리턴한다. → view파일이 사용자에게 보여진다.
서비스 → 컨트롤러에서 부른 서비스들의 메소드들에 따라 서비스를 구현하는데, 이 때 전체 DB와 관련있는 서비스들은 DAO객체를 이용하여 처리한다.
Controller 객체 구현
1.
컨트롤러 내에서 url을 매핑할 때 공통의 url이 존재하면, 해당 컨트롤러에 @RequestMapping("공통 url")을 붙인다.
@RequestMapping("/member")
public class MemberController{
...
}
여러 컨트롤러를 기능별로 구분하는데, 요청 파라미터가 같은 데이터로 올 때가 있다. 동일한 데이터를 중복해서 쓸 필요가 없고, 컨트롤러 클래스 위에서 requestmapping 을 써서 중복 url을 처리해주면 된다.
form태그에서 name값을 파라미터로 받아서 reqeust를 받는다.
2.
HttpServletRequest 를 대체하는 방법
@RequestParam 어노테이션을 사용한다
public String memLogin(Model model, @RequestParam("memId") String memId)
이랑
String memId = reqeust.getParamter("memId");
같다.
RequestParma어노테이션의 required = "flase" 이면 빈 칸이어도 상관없다. 근데 잘 안 쓰긴 함. 왜냐면 client측에서 다 처리하기 때문에
커맨드 객체를 이용하는 방법 : Member라는 클래스
→ form을 받을 때 name속성과 같은 값을 가지는 속성을 가지는 클래스를 하나를 만든다.
이 커맨드 객체(ex. member객체)를 이용하면 자동으로 setter가 실행되서 객체를 자동으로 채운다. 꺼내올 때는 getter를 써서 들고옴
이렇게 해서 view에 보낼 때는 어떻게 하냐 → 그대로 커맨드 객체를 이용해서 접근할 수 있다.
${member.memId}이런 식으로{member.memId}이런 식으로
3.
@ModelAttribute
커멘드 객체의 이름을 변경할 수 있고, 이렇게 변경된 이름은 뷰에서 커멘드 객체를 참조할 때 사용된다.
메소드 위에 ModelAttribute 어노테이션을 붙이고 이름을 붙이면, 컨트롤러 안에서 다른 메소드가 호출될 때, ModelAttribute 어노테이션을 붙인 이 메소드도 항상 같이 실행된다.
그리고 view단에서 ModelAttribute의 name에 해당하는 값으로 쓸 수 있다.
4.
커멘드 객체의 프로퍼티 데이터 타입
커멘드 객체에 들어오는 데이터가 사용자 정의 객체를 담는 리스트일 때
새로운 사용자 정의 객체를 설정하고 그 커멘드 객체를 사용하는 리스트를 객체로 사용한다. 중첩 커멘드 객체!
5.
ModelAndView
Model : View에 데이터만을 전달하기 위한 객체
ModelAndView: 데이터와 View의 이름을 함께 전달하는 객체
addObject
setViewName
사용할 때는 객체의 이름과 데이터를 뽑아서 쓴다.
세션과 쿠키
세션은 서버에서 연결 정보를 관리하는 반면 쿠키는 클라이언트에서 연결 정보를 관리하는 차이
1.
HttpServletRequest를 이용한 세션 사용
스프링 MVC에서 HttpServletRequest를 이용해서 세션을 이용하려면 컨트롤러의 메소드에서 파라미터로 HttpServletRequest를 받으면 된다
HttpSession session = request.getSession();
session.setAttribute("member",mem); // member의 속성에 mem의 값을 입력
2. HttpSession을 이용한 세션 사용
파라미터로 HttpSession을 받아 세션을 사용하는 방법, 반면 1번은 HttpServletRequest를 받은 후 getSession()으로 세션 얻음.
3. 세션 삭세
세션에 저장된 속성이 더 이상 필요가 없을 때
session.invalidate();
4. 주요 메소드
getId() : 세션 ID를 반환
setAttribute() : 세션 객체의 속성을 저장
getAttribute() : 세션 객체에 저장된 속성을 반환
removeAttribute() : 세션 객체에 저장된 속성을 제거
setMaxInactiveInternal() : 세션 객체에 유지시간을 설정
getMaxInactiveInternal() : 세션 객체의 유지시간을 반환
invalidate() : 세션 객체의 모든 정보를 삭제
5. 쿠키
Cookie genderCookie = new Cookie("gender", mall.getGender());
첫번째는 쿠키의 이름, 두 번째는 쿠키값을 넣어준다.
생성된 쿠키를 사용할 때
@CookieValue(value = "gender", required = false) Cookie genderCookie,
젠더에 대한 쿠키를 들고오면 genderCookie라고 하고 들고옴
value 속성 = 쿠키 이름을 나타내는데, 만약 value에 명시한 쿠키가 없을 경우 익셉션이 발생. required 속성으로 익셉션이 발생하지 않도록 할 수 있다.
리다이렉트, 인터셉트
컨트롤러에서 뷰를 분기하는 방법과 컨트롤러 실행 전/후에 특정 작업을 가능하게 하는 방법
1.
리다이렉트
지금 페이지에서 특정 페이지로 전환하는 기능
return("redirect:/");
2.
인터셉트
리다이렉트가 굉장히 많아지면 어떻게 하는가?
HandlerInterceptor를 이용해서 처리한다.
Request → DispatcherServlet → HandlerInterceptor(인터페이스)
HandlerInterceptor( preHandle(), postHandle(). afterCompletion() )
preHandle() → 컨트롤러 작업하기 전 ⇒ 가장 많이 쓰인다, 리다이렉트를 대체할 수 있음.
postHandle() → 컨트롤러 작업 후
afterCompletion() → 컨트롤러 & view 작업 후
HandlerInterceptorAdaptor → HandlerInterceptor 인터페이스를 구현한 클래스
스프링 설정 파일에서 클래스를 생성해서 사용해주면 된다.
<interceptors>
<interceptor>
<mapping path="/member/modifyForm"/>
<mapping path="/member/removeForm"/>
<!--
<mapping path="/member/**"/>
<exclude-mapping path="/member/joinForm"/>
<exclude-mapping path="/member/join"/>
<exclude-mapping path="/member/loginForm"/>
<exclude-mapping path="/member/login"/>
<exclude-mapping path="/member/logout"/>
<exclude-mapping path="/member/modify"/>
<exclude-mapping path="/member/remove"/>
-->
<beans:bean class="com.bs.lec21.member.MemberLoginInterceptor"/>
</interceptor>
</interceptors>
XML
복사
JDBC
기본 SQL →아니까 넘어가자
JDBC
드라이버 로드 , 커넥션 객체를 구하고, 질의 응답을 하고, 사용한 자원을 해제하는
JDBC의 단점을 보완한 JdbcTemplate