首页 > 解决方案 > 无法从我的过滤器类中的控制器类中正确获取会话对象属性值

问题描述

我正在使用 java Filter 类,我无法将我的会话对象从我的控制器类中获取到我的 Filter 中,因此我可以检查它的布尔值并执行代码。我需要检查会话属性“授权”是否等于 true。如果是这样,重定向到 index.jsp,而不是 login.html。

控制器类:

公共类 AuthController 扩展 HttpServlet {

@Override
public void doPost(HttpServletRequest request,
        HttpServletResponse response)
        throws ServletException, IOException {

    // Hardcoded for simplicity. A real world application would get these from a database.
    String username = "librarian";
    String password =  "sesame";

    String suppliedUsername = request.getParameter("username");
    String suppliedPassword = request.getParameter("password");

     boolean authorized = false;
    if (suppliedUsername != null
            && suppliedUsername.equals(username)
            && suppliedPassword != null
            && suppliedPassword.equals(password)) {
        authorized = true;
    }

    if (authorized == true) {
        request.getSession().setAttribute("authorized", true);
        response.sendRedirect("index.jsp");
    } else {
        response.sendRedirect("loginfailed.html");
    }
}

过滤器类:

公共类 AuthFilter 实现过滤器 {

private FilterConfig filterConfig = null;

@Override
public void init(FilterConfig filterConfig) {
    this.filterConfig = filterConfig;
}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

   chain.doFilter(request, response);

    HttpServletRequest httpRequest = (HttpServletRequest)request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;


    boolean authorized = Boolean.TRUE == request.getAttribute("authorized");
   //test authorized value
   System.out.println(authorized);
    if (authorized == false){

        httpResponse.sendRedirect("login.html");

    }
     if (authorized == true) {

        httpResponse.sendRedirect("index.jsp");

    }

当我调试时,我的授权值总是以错误结束,即使我使用有效凭据登录也是如此。我的问题似乎在这一行:

    boolean authorized = Boolean.TRUE == request.getAttribute("authorized");
   //test authorized value
   System.out.println(authorized);

标签: javasessionfiltercontrollerhttprequest

解决方案


推荐阅读