我正在使用 Spring Boot 和 MVC 开发一个 Web 应用程序。我有 Controller ,在每个 Controller 中我必须检查 session 是否存在。在 getAll 方法的示例中,我正在检查 session 是否存在,但我必须在每个方法、每个 Controller 中编写此检查代码。有什么捷径可以做到这一点吗?
@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;
}
}
}
最佳答案
您可以使用 Filter并将其应用于所有请求或仅应用于那些匹配特定模式的请求。
要检查 session ,您可以使用 HttpServletRequest.getSession(false)并检查是否为空。
关于java - Spring MVC 在每个请求之前检查 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57137095/