오늘 회사 동료가 알려준 방법인데, 꽤 유용할 것 같아서 이렇게 기록으로 남긴다.
package dreaminfra.ipams.web.assessment;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
@Controller
@SessionAttributes({"simpleForm"})
@RequestMapping("/simple")
public class SimpleController {
private final static String SIMPLE_FORM = "simpleForm";
/**
* 컨트롤러에서 @SessionAttribute({"simpleForm"}) 으로 선언한 simpleForm을 초기화하여
* Session에서 유지하기 위해 반드시 구현해줘야 하는 부분이다.
* @return
*/
@ModelAttribute(SIMPLE_FORM)
public SimpleForm createSimpleForm() {
return new SimpleForm();
}
@RequestMapping(value="/request", method=RequestMethod.GET)
public String request(Model model) {
/**
* Session에 SIMPLE_FORM을 생성하여 등록한다.
*/
model.addAttribute(SIMPLE_FORM, new SimpleForm());
return "/simple/response";
}
@RequestMapping(value="/response", method=RequestMethod.POST)
public String response(@ModelAttribute(SIMPLE_FORM) SimpleForm form, SessionStatus status) {
/**
* Session 에 등록된 SimpleForm 은 SessionStatus.setComplete()을 실행하기 전까지는
* Session에서 내부의 데이터를 유지하게 된다. SessionStatus.setComplete()을 실행하면
* Controller에서 선언해둔 SessionAttribute에 등록된 form이 초기화된다.
*/
status.setComplete();
return "redirect:/simple/request";
}
class SimpleForm {
private String name;
private String nickName;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
}
}
위에서 중요한 것은 Contoller 에서 선언한
SessionAttributes({"simpleForm"})
...
@ModelAttribute(SIMPLE_FORM)
public SimpleForm createSimpleForm() {
return new SimpleForm();
}...
model.addAttribute(SIMPLE_FORM, new SimpleForm());
...
session.setComplete()
부분이다.