-1

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
  • It looks like you having a different problem rather than `"SendRedirect() not working jsp throwing Null Pointer Exception"` – Roman C Sep 20 '22 at 19:23
  • I do not want to invoke methods of user of type UserBean if its null... So i want to redirect when it's null.... and i think i have written correct logic in JSP scriptlet tag.... What's the error, please help or share this question so that i can continue my work – Syed Hamed Sep 20 '22 at 19:27
  • If you don't want to invoke methods then don't do it. It's not suposed to redirect from the view to the not authorized page. The error is beyond the control of the scriptlet variable which even has no any scope and you methods are called either you send redirect to the browser or not. The browser didn't get a redirect signal while jsp is rendered. – Roman C Sep 20 '22 at 19:40
  • please explain more... Didn't understand – Syed Hamed Sep 20 '22 at 19:42

1 Answers1

0

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.

JM.
  • 21
  • 1