tunc
tunc

Reputation: 51

Spring MVC Session check before every request

I am developing a web app using spring boot and mvc. I have controllers and in every controller i have to check if session is exist. In example in getAll method i am checking if session is existing but i have to write this check code in every method , every controller. Is there any shortcut to do that?

@Controller
@RequestMapping("/Sale")
public class SaleController
{
    @Autowired
    private SaleRepository saleRepository;
    @GetMapping
    public ModelAndView getAll(@SessionAttribute(required=false) User user)
    {
        if(user==null)
            return new ModelAndView("redirect:/");
        else
        {
            ModelAndView modelAndView=new ModelAndView("/view/sales.jsp");
            List<Sale> sales=saleRepository.findAll();
            modelAndView.addObject("sales",sales);
            return modelAndView;
        }
    }
}

Upvotes: 0

Views: 2363

Answers (1)

Mike
Mike

Reputation: 5142

You can use a Filter and apply it to all requests or only those matching a specific pattern.

To check for a session you would use HttpServletRequest.getSession(false) and check for null.

Upvotes: 2

Related Questions