Computer Science/Spring

#9 HTTP Session 사용

꿈꾸는어린이 2018. 6. 16. 19:24

HTTP Session 사용

@SessionAttributes

  • controller 클래스에 적용

  • 지정된 이름 또는 타입의 model 객체들을 session에 저장 및 사용

  • controller가 임시적으로 유지, 공유하고자 하는 model 객체들을 저장하기 위해 사용

    -> 주로 여러 화면을 통해 단계적으로 입력되는 데이터들을 보관 시 유용

  • 여러 controller 사이의 데이터 공유는 HttpSession 이용

    (ex. 사용자 인증 정보)

  • SessionStatus interface - setComplete() : session종료(session에 저장되어 있는 모든 객체 삭제)

<br>

  @Controller
@RequestMapping("/account/create.do")
@SessionAttributes("member") //member객체를 session에 저장 및 공유
public class CreateAccountController {

@ModelAttribute("memeber") //MemberInfo(command)객체 이름 지정
public MemberInfo formBacking(HttpServletRequest request) {
if (request.getMethod().equalsIgnoreCase("GET")) {
MemberInfo memeberInfo = new MemberInfo();
Address address = new Address();
address.setZipcode(autoDetectZipcode(request.getRemoteAddr()));
memeberInfo.setAddress(address);
return memeberInfo; //session에 member라는 이름으로 저장됨
} else {
return new MemberInfo();
}
}

@RequestMapping(method = RequestMethod.GET)
public String form() {
return "account/creationForm";
     //formBacking()에서 생성 및 초기화된 "member"객체 참조가 view에 전달됨
}

@RequestMapping(method = RequestMethod.POST)
public String submit(@ModelAttribute("member") MemberInfo memberInfo,
            //session에 저장된 "member"객체 찾아 form 입력 값 저장 후 memberInfo로 참조됨
BindingResult result, SessionStatus status) {
new MemberInfoValidator().validate(memberInfo, result);
if (result.hasErrors()) {
return "account/creationForm";
}
status.setComplete(); //session 종료("member"객체 참조 삭제)
return "account/created"; //"member"객체 참조가 view에 전달됨
}
}

<br>

★★ session에 "member" 객체가 이미 존재할 경우 formBacking() method는 실행되지 않음.

따라서 하나의 "member" 객체를 공유 가능

<Br>

Session 이용한 4단계 요청 처리

  1. EventForm (domain class) 생성 : 이벤트 정보 입력 받아 저장, 공유할 객체

  2. controller

  
@Controller
@SessionAttributes("eventForm") //session에 저장할 이름
public class EventCreationController {

private static final String EVENT_CREATION_STEP1 = "event/creationStep1";
private static final String EVENT_CREATION_STEP2 = "event/creationStep2";
private static final String EVENT_CREATION_STEP3 = "event/creationStep3";
private static final String EVENT_CREATION_DONE = "event/creationDone";

@ModelAttribute("eventForm") //EventForm 객체 생성하여 세션에 저장
public EventForm formData() {
return new EventForm();
}
//step1()에서 직접 생성 후 Model 객체에 저장하여 사용하는 것도 가능

//step1
@RequestMapping("/newevent/step1")
public String step1() {
return EVENT_CREATION_STEP1;
}

 
//step2
@RequestMapping(value = "/newevent/step2", method = RequestMethod.POST)
public String step2(@ModelAttribute("eventForm") EventForm formData, BindingResult result) {
new EventFormStep1Validator().validate(formData, result);
if (result.hasErrors())
return EVENT_CREATION_STEP1;
return EVENT_CREATION_STEP2;
}

//step3에서 step2로 되돌아옴 ->그대로 유지
@RequestMapping(value = "/newevent/step2", method = RequestMethod.GET)
public String step2FromStep3(@ModelAttribute("eventForm") EventForm formData) {
return EVENT_CREATION_STEP2;
}

//step3
@RequestMapping(value = "/newevent/step3", method = RequestMethod.POST)
public String step3(@ModelAttribute("eventForm") EventForm formData, BindingResult result) {
ValidationUtils.rejectIfEmpty(result, "target", "required");
if (result.hasErrors())
return EVENT_CREATION_STEP2;
return EVENT_CREATION_STEP3;
}

//step4
@RequestMapping(value = "/newevent/done", method = RequestMethod.POST)
public String done(@ModelAttribute("eventForm") EventForm formData, SessionStatus sessionStatus) {
sessionStatus.setComplete();//session 삭제 : 삭제 전 입력정보는 DB에 입력할 것
return EVENT_CREATION_DONE;
}

}

<br>

  1. view step1

  
<form:form commandName="eventForm" action="step2"> <!-- command 객체 지정 -->

<label for="name">이벤트 명</label>:
<input type="text" name="name" id="name" value="${eventForm.name}"/>
<form:errors path="name"/><br/>

<label for="type">타입</label>:
<select name="type" id="type">
<option value="">선택하세요</option>
<c:forEach var="type" items="<%= EventType.values() %>">
<option value="${type}" ${eventForm.type == type ? 'selected' : ''}>${type}</option>
</c:forEach>
</select>
<form:errors path="type"/><br/>

<label>이벤트 기간</label>:
<input type="text" name="beginDate" value='<fmt:formatDate value="${eventForm.beginDate}" pattern="yyyyMMdd"/>'/>부터
<input type="text" name="endDate" value='<fmt:formatDate value="${eventForm.endDate}" pattern="yyyyMMdd"/>'/>까지
<form:errors path="beginDate"/><br/>
<form:errors path="endDate"/><br/>

<input type="submit" value="다음 단계로" />
</form:form>
<br>
세션 존재 여부: <%= session.getAttribute("eventForm") != null ? "존재" : "없음" %>

<p><a href="<c:url value='/index' />">Go to index</a></p>


<br>

view step2

  
<body>

<form:form commandName="eventForm" action="step3">

<label>적용 회원 등급</label>:
<label><input type="radio" name="target" value="all" ${eventForm.target == 'all' ? 'checked' : '' }/>모든 회원</label>
<label><input type="radio" name="target" value="premium" ${eventForm.target == 'premium' ? 'checked' : '' } />프리미엄 회원</label>
<form:errors path="target"/><br/>
<br/>
<a href="step1">[이전 단계로]</a>
<input type="submit" value="다음 단계로" />
</form:form>
<br>
세션 존재 여부: <%= session.getAttribute("eventForm") != null ? "존재" : "없음" %>

<p><a href="<c:url value='/index' />">Go to index</a></p>
</body>


<br>

view step3

  
<body>

<form:form commandName="eventForm" action="done">

<label>이벤트 명</label>: <c:out value="${eventForm.name}" /> <br>
<label>타입</label>: ${eventForm.type} <br>

<label>이벤트 기간</label>:
<c:if test="${eventForm.beginDate != null}">
<fmt:formatDate value="${eventForm.beginDate}" pattern="yyyyMMdd"/>부터
</c:if>
<c:if test="${eventForm.endDate != null}">
<fmt:formatDate value="${eventForm.endDate}" />까지
</c:if>
<br>

<label>적용 회원 등급</label>: ${eventForm.target == 'all' ? '모든 회원' : '프리미엄 회원' }
<br>
<br>
<a href="step2">[이전 단계로]</a>
<input type="submit" value="이벤트 생성 완료" />
</form:form>
<br>
세션 존재 여부: <%= session.getAttribute("eventForm") != null ? "존재" : "없음" %>

<p><a href="<c:url value='/index' />">Go to index</a></p>
</body>


'Computer Science > Spring' 카테고리의 다른 글

#10 Tiles  (0) 2018.06.16
#8 Form 입력 값 검증  (0) 2018.06.16
#7 Model Data  (0) 2018.05.26
#6 Command 객체 이용한 Form 전송 처리  (2) 2018.05.25
#5 Spring MVC 구조  (0) 2018.05.25