WarcraftZS
WarcraftZS
采纳率0%
2019-08-26 14:30 阅读 349

mvc启动报错(baseController注入的request是null)

自己学习spingboot,搭建的mvc项目,我的想法是:
登录的时候保存loginUser,然后在BaseController获取loginUser,所有的controller继承BaseController,这样在其他的controller中就可以直接使用loginUser。
现在项目启动报错,request是null,
希望帮忙看一下我这么写是有什么问题?或者有没有别的办法可以实现我想要的结果

public class BaseController {

    private static Logger log = LoggerFactory.getLogger(BaseController.class);

    @Autowired(required = false)
    private HttpServletRequest request;

    public  LoginUser loginUser = (LoginUser) request.getSession().getAttribute("loginUser");


    public void  saveLoginUserInBase(LoginUser loginUser){
        request.getSession().setAttribute("loginUser",loginUser);
    }
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

3条回答 默认 最新

  • nevancc 孙大胜 2019-08-26 14:49

    request是存在你controller里的方法里的参数的,例如

    public void  saveLoginUserInBase(HttpServletRequest request, LoginUser loginUser){
            request.getSession().setAttribute("loginUser",loginUser);
        }
    

    正常只要你的controller使用@Controller注解后,你的每个方法里都存在request和response(HttpServletResponse)

    点赞 评论 复制链接分享
  • tiankongzhichenglyf tkzc_shark 2019-08-26 14:53
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder .getRequestAttributes()).getRequest();
    
    点赞 评论 复制链接分享
  • renkai721 renkai721 2019-08-26 15:20
    import javax.servlet.http.HttpServletRequest;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.web.context.request.RequestContextHolder;
    import org.springframework.web.context.request.ServletRequestAttributes;
    
    public class BaseController {
        private final static String LOGIN_USER = "loginUser";
        private static Logger log = LoggerFactory.getLogger(BaseController.class);
    
        public static LoginUser getLoginUserInBase() {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                    .getRequest();
            return (LoginUser) request.getAttribute(LOGIN_USER);
        }
        public static void saveLoginUserInBase(LoginUser loginUser) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                    .getRequest();
            request.getSession().setAttribute(LOGIN_USER, loginUser);
        }
    }
    

    你试下这个代码,不过不建议这样的封装,springboot可以用aop或者filter或者intercepter直接进行处理,如果没有获取到就跳转到登录页面。

    点赞 评论 复制链接分享

相关推荐