Servlet过滤器提供NullPointerException

时间:2014-09-02 10:43:45

标签: java nullpointerexception servlet-filters

我创建了一个java Web应用程序,并使用过滤器来防止未经授权的访问,但它无法正常工作。成功登录后,它应该回家.jsp但不会去。当我运行应用程序时,它从 AuthFilter.java 中的init方法开始执行,在init方法之后,控件转到 Method.java netbeans预定义方法。 在浏览器中显示以下错误:

HTTP Status 500 -
type Exception report
message
description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
    Filters.AuthFilter.doFilter(AuthFilter.java:47)

注意Apache Tomcat / 8.0.3日志中提供了根本原因的完整堆栈跟踪。这是代码。

LoginServlet.java

package Servlets;

//all important files are imported

public class LoginServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String user = "king";
        String pass  = "king";

        String uname = request.getParameter("user");
        String upass = request.getParameter("pwd");

        if(uname.equals(user) && upass.equals(pass))
        {
            HttpSession session = request.getSession(true);
            session.setAttribute("username", uname);
//            Cookie userName = new Cookie("user", user);
//            userName.setMaxAge(10*60);
//            response.addCookie(userName);
            response.sendRedirect("home.jsp");
        }
        else
        {
            RequestDispatcher rd = getServletContext().getRequestDispatcher("index.jsp");
            PrintWriter out = response.getWriter();
            out.println("<font color=red>Either user name or password is wrong.</font>");
            rd.include(request, response);
        }
    }



}

AuthFilter.java

package Filters;

public class AuthFilter implements Filter {

    ArrayList<String> array = new ArrayList<>();
    private ServletContext context;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {
        System.out.println("2");
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        String uri = req.getRequestURI();

        HttpSession session = req.getSession(false);
        boolean r = false;
        if(array.contains(uri))
        {
            r = true;
        }
        System.out.println(" r result my = " + r);
        Object o = session.getAttribute("username");
        System.out.println("abcde = " + o);
        if(o == null)
            System.out.println("null session my = " + session);
        else
            System.out.println(" not null session my = " + session);
//        System.out.println("session getAttribute = " + session.getAttribute("username"));
        if(o == null && r == true)
        {
            System.out.println("unauthorized");
            r = false;
            res.sendRedirect("index.jsp");
        }
        else
        {
            System.out.println("auth");
            chain.doFilter(request, response);
        }

    }

    @Override
    public void destroy() {
        System.out.println("3");
    }

    @Override
    public void init(FilterConfig filterConfig) {
        System.out.println("1");
        this.context = filterConfig.getServletContext();
        array.add("/MyFilter/demo.jsp");
        array.add("/MyFilter/more.jsp");
        array.add("/MyFilter/home.jsp");
        System.out.println("show array list:-\n");
        for (String array1 : array) {
            System.out.print(array1 + "\n");
        }
        this.context.log("AuthenticationFilter initialized");
    }

}

Web.xml中

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <filter>
        <filter-name>AuthFilter</filter-name>
        <filter-class>Filters.AuthFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>AuthFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>Servlets.LoginServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>LogoutServlet</servlet-name>
        <servlet-class>Servlets.LogoutServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/LoginServlet</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>LogoutServlet</servlet-name>
        <url-pattern>/LogoutServlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

2 个答案:

答案 0 :(得分:1)

在您的servlet中,您尝试使用request.getSession(false)访问当前会话。这不会创建任何会话,因此在首次访问时,您只会得到null表示没有初始化会话。但是你没有测试它并立即使用它,所以错误。您应该使用request.getSession(true)来确保在不存在的情况下创建会话,同时正确使用现有会话。

答案 1 :(得分:0)

可以在

之后检查会话是否为空
HttpSession session = req.getSession(false);

给出false将不会创建新会话,因此结果可以为null。这将导致以下行的空指针异常

Object o = session.getAttribute("username");