我创建了一个Java Web应用程序,并使用过滤器来防止未经授权的访问,但它无法正常工作。成功登录后,它应该进入home.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)


note注意在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>

最佳答案

在您的servlet中,您尝试使用request.getSession(false)访问当前会话。那不会创建任何会话,因此,在第一次访问时,您只会得到一个null,表示未初始化任何会话。但是您不对其进行测试并立即使用它,因此会出现错误。相反,您应该使用request.getSession(true)来确保在不存在会话的情况下正确地使用现有会话来创建会话。

关于java - Servlet筛选器提供NullPointerException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25621501/

10-13 05:37