@SessionAttributes с @GetMapping - PullRequest
       21

@SessionAttributes с @GetMapping

0 голосов
/ 15 февраля 2019

У меня есть контроллер с SessionAttributes, который отображается на класс и ModelAttribute, которые получают объект из БД, если он не представлен, и устанавливают его в атрибут сеанса, но по какой-то причине он не работает должным образом.
Контроллер

@Controller
@SessionAttributes(types = Student.class)
public class UserController {
private Student cachedStudent;

..... some code

@GetMapping("/profile")
    public String profile(@ModelAttribute Student student, Model model) {
        model.addAttribute("student", student);
        return "profile";
    }

@ModelAttribute
    public Student getStudent() {
        if (nonNull(cachedStudent)
                && cachedStudent.getUsername().equals(SecurityContextHolder.getContext().getAuthentication().getName())) {
        return cachedStudent;
        }
        if (nonNull(SecurityContextHolder.getContext().getAuthentication().getName()) &&
                !Objects.equals(SecurityContextHolder.getContext().getAuthentication().getName(), "anonymousUser")) {
            cachedStudent = studentService.findByUsername(SecurityContextHolder.getContext().getAuthentication().getName());
        return cachedStudent;
        }
        return new Student();
    }
}

Как я знаю каждый раз, когда вызывает объект Student в контроллере с помощью @ModelAttribute, он вызывает метод, аннотированный этой аннотацией, и сбрасывает / обновляет сеанс attr,Но результатом является пустой объект, а cachedStudent присутствует.

...