MVC模式中,Controller和Service之间使用HttpSession哪个更好?
In MVC pattern, which is better to use HttpSession between Controller or Service?
目前,通过在服务中声明 HttpSession,创建会话并检索键的值。
@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");
}
以上表述是否正确?或者首先在 Controller 中验证会话是否正确?
在spring mvc session一般用在controller上。在 spring 中,您可以使用 @SessionAttributes 注释在 class 范围内定义会话属性,在方法范围内使用 @ModelAttribute 注释。
@Controller
@SessionAttributes("login-user")
@RequestMapping("/formAnswer")
public class FormAnswerController {
@RequestMapping("/**")
public String handleFromAnswerRequest(@ModelAttribute("login-user") LoginUser loginUser,
Model model,
HttpServletRequest request) {
.......
}
}
目前,通过在服务中声明 HttpSession,创建会话并检索键的值。
@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");
}
以上表述是否正确?或者首先在 Controller 中验证会话是否正确?
在spring mvc session一般用在controller上。在 spring 中,您可以使用 @SessionAttributes 注释在 class 范围内定义会话属性,在方法范围内使用 @ModelAttribute 注释。
@Controller
@SessionAttributes("login-user")
@RequestMapping("/formAnswer")
public class FormAnswerController {
@RequestMapping("/**")
public String handleFromAnswerRequest(@ModelAttribute("login-user") LoginUser loginUser,
Model model,
HttpServletRequest request) {
.......
}
}