Access session scoped variable in spring interceptor

北城以北 提交于 2020-01-04 18:14:12

问题


How can i access session scoped variable in spring interceptor?

Session scoped class:

@Component
@Scope("session")
public class User {
}

Controller:

@Controller
@RequestMapping("/restricted")
@Scope("request")
public class RestrictedController {
    @Autowired
    private User user;
}

Dispatcher servlet:

<mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/restricted/*"/>
            <bean class="com.interceptors.RestrictedInterceptor" />
        </mvc:interceptor>
    </mvc:interceptors>

Interceptor class:

public class RestrictedInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
    }
}

In prehandle i want to check if user is logged in (some other checks as well), how can i access session scoped user variable here? Autowiring user in Interceptor class throws exception.


回答1:


You should be able to access your session-scoped user using the following code:

request.getSession().getAttribute("scopedTarget.user");

See related post here and org.springframework.aop.scope.ScopedProxyUtils class.



来源:https://stackoverflow.com/questions/32283450/access-session-scoped-variable-in-spring-interceptor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!