SPRING MVC: определенный HttpSession в одном методе недоступен для другого метода - PullRequest
0 голосов
/ 29 февраля 2020

У меня проблема с Httpsession, который я реализовал в проекте Spring MVC.

Прежде всего, после успешного входа пользователя я возьму объект Httpsession в loginAuthentication контроллер и установить атрибут с именем и значением, которое я хочу. (Показано на следующем рисунке).

A. java файл контроллера,

@RequestMapping(value="login-authentication", method = RequestMethod.POST)
    public String authentication(@Valid @ModelAttribute("systemAccount") SystemAccount systemAccount,
                                 BindingResult bindingResult, Model model, HttpServletRequest request){
        if (bindingResult.hasErrors()) {
            model.addAttribute(GenericConstant.MessageAttributeName.ERROR_MSG_NAME.toValue(), SystemMessage.SystemException.LOGIN_INCORRECT_USERNAME_PASSWORD.toValue());
            model.addAttribute("systemAccount", new SystemAccount());
            return "index";
        }else {
            if (systemAccountService.authenticate(systemAccount.getUsername(), systemAccount.getPassword()) != null &&
                    !"".equals(systemAccountService.authenticate(systemAccount.getUsername(), systemAccount.getPassword()))) {

                SystemAccount dbSystemAccount = systemAccountService.authenticate(systemAccount.getUsername(), systemAccount.getPassword());

                request.setAttribute(SessionAttribute.AttributeName.LOGIN_ACC_ID.toValue(),dbSystemAccount.getAccountID());
                //check account role
                if(dbSystemAccount.getCounterStaff()!= null && !"".equals(dbSystemAccount.getCounterStaff())){
                    CounterStaff counterStaff =  dbSystemAccount.getCounterStaff();
                    request.setAttribute(SessionAttribute.AttributeName.LOGIN_ACC_NAME.toValue(), counterStaff.getStaffName());
                    request.setAttribute(SessionAttribute.AttributeName.LOGIN_ACC_ROLE.toValue(), GenericConstant.SystemRole.COUNTER_STAFF.toValue());

                }else if(dbSystemAccount.getCustomer()!= null && !"".equals(dbSystemAccount.getCustomer())){
                    Customer customer = dbSystemAccount.getCustomer();
                    request.setAttribute(SessionAttribute.AttributeName.LOGIN_ACC_NAME.toValue(), customer.getCustomerName());
                    request.setAttribute(SessionAttribute.AttributeName.LOGIN_ACC_ROLE.toValue(), GenericConstant.SystemRole.CUSTOMER.toValue());

                }else if(dbSystemAccount.getManager()!= null && !"".equals(dbSystemAccount.getManager())){
                    Manager manager = dbSystemAccount.getManager();
                    request.setAttribute(SessionAttribute.AttributeName.LOGIN_ACC_NAME.toValue(), manager.getManagerName());
                    request.setAttribute(SessionAttribute.AttributeName.LOGIN_ACC_ROLE.toValue(), GenericConstant.SystemRole.MANAGER.toValue());

                }else if(dbSystemAccount.getDoctor()!= null && !"".equals(dbSystemAccount.getCounterStaff())){
                    Doctor doctor = dbSystemAccount.getDoctor();
                    request.setAttribute(SessionAttribute.AttributeName.LOGIN_ACC_NAME.toValue(), doctor.getDoctorName());
                    request.setAttribute(SessionAttribute.AttributeName.LOGIN_ACC_ROLE.toValue(), GenericConstant.SystemRole.DOCTOR.toValue());
                }

                request.setAttribute(SessionAttribute.AttributeName.LOGIN_DATE.toValue(), DateTimeUtil.getCurrentDate());
                return "mainPage";
            }else {
                model.addAttribute(GenericConstant.MessageAttributeName.ERROR_MSG_NAME.toValue(), SystemMessage.SystemException.LOGIN_INCORRECT_USERNAME_PASSWORD);
                model.addAttribute("systemAccount", new SystemAccount());
                return "index";
            }
        }
    }

После того, как все будет готово, контроллер будет перейти пользователя на главную страницу и главную страницу, которая может получить доступ ко всем определенным переменным без проблем. (На следующем рисунке показан контроллер, сопоставленный с mainPage).

A. java файл контроллера,

@RequestMapping(value = "/mainPage", method = RequestMethod.GET)
    public String renderMainPageView(Model model, HttpServletRequest request) {
        if(request.getAttribute(SessionAttribute.AttributeName.LOGIN_CHECK.toValue()) != null) {
            model.addAttribute(SessionAttribute.AttributeName.LOGIN_ACC_ID.toValue(),
                    request.getAttribute(SessionAttribute.AttributeName.LOGIN_ACC_ID.toValue()));
            model.addAttribute(SessionAttribute.AttributeName.LOGIN_ACC_NAME.toValue(),
                    request.getAttribute(SessionAttribute.AttributeName.LOGIN_ACC_NAME.toValue()));
            model.addAttribute(SessionAttribute.AttributeName.LOGIN_ACC_ROLE.toValue(),
                    request.getAttribute(SessionAttribute.AttributeName.LOGIN_ACC_ROLE.toValue()));
            model.addAttribute(SessionAttribute.AttributeName.LOGIN_DATE.toValue(),
                    request.getAttribute(SessionAttribute.AttributeName.LOGIN_DATE.toValue()));
            return "mainPage";
        }else {
            model.addAttribute("systemAccount", new SystemAccount());
            return "index";
        }
    }

В меню навигации главной страницы, я нажимаю на выбор, чтобы направить меня, чтобы добавить менеджер веб-страницы. (Ниже показана ссылка).

<a href="addManager" target="ifrm" >Add New Account</a>

Контроллер, сопоставленный со ссылкой (GET), способной обнаруживать. Однако этот контроллер (renderAddManagerView) не распознает сеанс HTTP, который я определил ранее, когда пытаюсь получить доступ с использованием метода getAttribute в условии if. Он продолжает показывать нулевое значение (показано на следующем рисунке.

B. java файл контроллера,

@RequestMapping(value = "/addManager", method = RequestMethod.GET)
    public String renderAddManagerView(Model model, HttpSession httpSession) {
        if(httpSession.getAttribute(SessionAttribute.AttributeName.LOGIN_CHECK.toValue()) != null) {
            model.addAttribute("manager", new Manager());
            model.addAttribute(FormSelectionValue.FormSelectionAttributeName.COUNTRY_SELECTION.toValue(), FormSelectionValue.COUNTRY_SELECTION_LIST);
            model.addAttribute(FormSelectionValue.FormSelectionAttributeName.GENDER_SELECTION.toValue(), FormSelectionValue.GENDER_SELECTION_LIST);
            return "addManager";
        }else {
            model.addAttribute("systemAccount", new SystemAccount());
            return "index";
        }
    }

Итак, я не уверен, что является причиной для моего кода, и сообщение об ошибке не отображается.

1 Ответ

1 голос
/ 01 марта 2020

Я решил проблему, используя HttpServletRequest вместо HttpSession. Теперь мой сеанс не будет потерян даже при перенаправлении или переходе на любые страницы в JSP.

Примерно так:

@RequestMapping("/renderview", method = RequestMethod.GET)
@Controller
public class TestController {
    @RequestMapping(method = RequestMethod.GET)
    public String myMethod(HttpServletRequest request)
    {
        request.getSession().setAttribute("mySession", "XXX");
        return "jspview";
    }
}

Ссылка: Установка переменной сеанса spring mvc 3

...