SendRedirect() not working jsp throwing Null Pointer Exception

Viewed 28

please help me whats stopping my program from running/... I have retrieved user_details of type UserBean and at the same time, I want to redirect my current JSP file) to login.jsp if its null... but i think it isn't working... Its still trying to retrieve values if even my retrieved object is null... Please help me with reason... I'm stuck here since 2 days.

Jsp Part where I have given redirecting logic:

<%
UserBean user = (UserBean) session.getAttribute("user_details");
if (user == null) {
response.sendRedirect("login.jsp");
    System.out.println(request.getContextPath());}
%>

Jsp part where i want to retrieve values of user object : (i want values only when user is not null )

                       <tr>
                            <td>Name</td>
                            <td><%=user.getName()%></td>
                        </tr>
                        <tr>
                            <td>About</td>
                            <td><%=user.getAbout() %></td>
                        </tr>
                        <tr>
                            <td>Email</td>
                            <td><%=user.getEmail() %></td>
                        </tr>
                        <tr>
                            <td>Gender</td>
                            <td><%=user.getGender() %></td>
                        </tr>

Exception thrown :

java.lang.NullPointerException: Cannot invoke "com.blog.model.UserBean.getId()" because "user" is null
1 Answers

This is what i usually do when i need to get the current user data. If there is no user in session i call a redirect to the login form.

I declare usebeans in a jsp tag, this way it declares itself and the value is filled by the browser.

<jsp:useBean id="user" scope="session" class="com.mypackage.myuserclass"/>
<%
if(user == null){
        response.sendRedirect("/login/");
        response.flushBuffer();
}else{

/**
*All your logic to do when there is a valid user.
*/

}

Let my know if this were helpful.

Related