Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring mvc 如何避免将HttpSession放在Spring控制器的每个方法中?_Spring Mvc - Fatal编程技术网

Spring mvc 如何避免将HttpSession放在Spring控制器的每个方法中?

Spring mvc 如何避免将HttpSession放在Spring控制器的每个方法中?,spring-mvc,Spring Mvc,在控制器的方法中,我需要从会话中检索一些数据(通常是用于用户权限和网页的每用户自定义的ID),我编写如下方法: @RequestMapping("something") public ModelAndView doSomething(HttpSession session) throws AuthorizationException{ PerUserModelBean bean = getSessionRelatedInfo(session); bean.checkPermissions()

在控制器的方法中,我需要从会话中检索一些数据(通常是用于用户权限和网页的每用户自定义的ID),我编写如下方法:

@RequestMapping("something")
public ModelAndView doSomething(HttpSession session) throws AuthorizationException{

PerUserModelBean bean = getSessionRelatedInfo(session);

bean.checkPermissions();



...do my stuff...

}

这很无聊,因为我必须为每个方法重复session参数,并且必须将代码放在每个方法的开头。不仅无聊,如果我想改变它,我必须跨越所有的方法并改变它。我希望会话信息检索和checkPermissions方法在我的方法之前被自动调用,然后根据会话内容自动填充bean变量(可能是threadlocal?)。有没有办法做到这一点

将下面的方法放在一个超类中,您可以将它用作通用功能的基础。我确信您已经有了一个,所以所有子类都将继承它

对于在每次方法执行之前执行它:您可以使用过滤器/拦截器/AOP,其他人可能会给您提供更准确的想法

protected HttpSession getSession(){
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return attr.getRequest().getSession();
    }

您应该将这种类型的“重复”代码放在
Servlet过滤器
springmvc拦截器
中。这样,如果用户登录与您的应用程序相关,您将能够强制用户登录。

您说得对,基本控制器已经就位。我不知道RequestContextHolder的事。。。。谢谢