Issue
Currently, by declaring HttpSession inside Service, session is created and the value for the key is retrieved.
@Service
@RequiredArgsConstructor
public class FormAnswerService {
private final FormAnswerRepository formAnswerRepository;
private final FormContentService formContentService;
private final MemberService memberService;
private final HttpServletRequest request;
public List<Long> createFormAnswer(Map<Long,String> answer) {
List<Long> formAnswerIdList = new ArrayList<>();
HttpSession httpSession = request.getSession();
Long memberId;
if(httpSession.getAttribute("login-user") != null) {
memberId = (Long)httpSession.getAttribute("login-user");
}
Is the above expression correct? Or is it correct to validate session in Controller in the first place?
Solution
In spring mvc session is usually used on controller. In spring you can use @SessionAttributes annotation to define session attributes on class scope and @ModelAttribute annotation in method scope.
@Controller
@SessionAttributes("login-user")
@RequestMapping("/formAnswer")
public class FormAnswerController {
@RequestMapping("/**")
public String handleFromAnswerRequest(@ModelAttribute("login-user") LoginUser loginUser,
Model model,
HttpServletRequest request) {
.......
}
}
Answered By - Trực Nguyễn Chánh
Answer Checked By - Candace Johnson (JavaFixing Volunteer)