King
King

Reputation: 51

Servlet Filter gives NullPointerException

I have created a java web app and used filter to prevent unauthorized access but it is not working. After successfully login it should go home.jsp but not going. when I run the app it start execution from init method in AuthFilter.java and after init method the control gone to Method.java netbeans predefined method. In browser following error is shown:

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 The full stack trace of the root cause is available in the Apache Tomcat/8.0.3 logs. Here is the code.

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>

Upvotes: 1

Views: 5962

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 149035

In your servlet, you try to access current session with request.getSession(false). That does not create any session, so at first access you only get a null saying that no session is initialized. But you do not test it and use it immediately so the error. You should instead use request.getSession(true) to ensure that a session will be created if not existent, while correctly using an existing one.

Upvotes: 1

Sezin Karli
Sezin Karli

Reputation: 2525

Can you check if session is null or not after

HttpSession session = req.getSession(false);

giving false will not create a new session and thus the result can be null. Which will result in a null pointer exception the following line

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

Upvotes: 0

Related Questions