If session exist or not - java

I am trying to write my first app on Google App Engine, I was trying to maintain a session, I created a login page on submit, it call to a servlet, servlet validates the user and create a new session using the following code.
void createSession(String Username) {
getThreadLocalRequest().getSession(true).setAttribute("Username", Username);
}
login page after calling the servlet redirects to some page i.e. abc.jsp, my abc.jsp page contains
<body><%
try {
if (request.getSession(false) == null) {
} else {
%>
Welcome to
<%=session.getAttribute("Username")%>
<%
if (session.getAttribute("Username").equals("")) {
%>
<b>Login </b>
<%
} else {
%>
<b>Logout</b>
<%
}
}
} catch (Exception e) {
}
%></body>
it works fine, but when I access abc.jsp without creating a session it is throwing an exception at this if (session.getAttribute("Username").equals("")) line, I dunno why kindly help me. I think it dont detect if session exists. but I have read so many threads like this It gave me this solution, I dunno what I am doing wrong.

As far as I remember
session.getAttribute("xyz")
returns null if the attribute does not exist...
so your NullPointerException occurs because you try to call equals on null.
I suggest to do a check on your attribute itself before validating its content:
if (session.getAttribute("Username") == null || session.getAttribute("Username").equals(""))

<%
if (session.getAttribute("Username") != null) {
…
}
%>

Before to check session's attributes, you have to see the session itself.
So, first:
HttpSession session = request.getSession(false);
if(session != null){...}
and then,
if(session.getAttribute("xyz") != null){...}
Better solution might be both in one line:
if(session != null && session.getAttribute("xyz") != null)
returns null if the attribute does not exist... so your
NullPointerException occurs because you try to call equals on null.
Obviously, it's strictly recommended to check your attribute, before validating its content (as above).

It Worked For me. Try This
String userName;
userName = (String)session.getAttribute("uname");
if (session.getAttribute("userName").equals(""))

Related

Losing Session Variable forwarding from jsp to servlet

I'm struggling with a rather troublesome problem. I'm making a web application using the following jsp/servlets.
GameServlet
Scene.jsp
PageServlet
GameServlet creates a new HttpSession and then sets a number of attributes I expect to use later.
GameServlet then forwards to Scene.jsp using the following code:
HttpSession session = request.getSession();
session.setAttribute("cur_game", game);
session.setAttribute("logic", logic);
session.setAttribute("cur_scene", scene);
session.setAttribute("session_id", session.getId());
out.println("Loaded session attributes");
if (debug == null) {
String target = "/Scene.jsp";
RequestDispatcher rd = request.getRequestDispatcher(target);
rd.forward(request, response);
}
In Scene.jsp I display the session id for later comparison. This works and also displays the other attributes in the session.
Then a button calls a function using the following code:
<script>
function gotoPage(target)
{
Str = "PageServlet?page=" + target;
window.location = Str;
}
</script>
However PageServlet doesn't seem to recognise the previous session. I check with this with the following code:
HttpSession sesh = request.getSession(false);
if(sesh==null)
out.println("Session is Null!");
else
out.println("<br/>Session id: " + sesh.getId());
And currently it displays that "Session is Null"
If anybody could provide some help it would greatly appreciated!
Many Thanks
Alex

Transform jsp to java code

I need java code for this jsp line code.
I know how to make it for scope "page" or "application" but i really dont know how it works with "session"
<jsp:useBean id=”pera” class=”beans.User” scope=”sesion”>
This is Solution.
beans.User user = null;
synchronized (application) {
user = (beans.User) _jspx_page_context.getAttribute("user",
PageContext.APPLICATION_SCOPE);
if (user == null){
user = new beans.User();
_jspx_page_context.setAttribute("user", user,
PageContext.APPLICATION_SCOPE);
}
}

How to detect expired session vs. no session

The requirement is this: When a user session is expired, call expired.htm page, but on the first connection to the web site, show login.htm.
I tried using a filter but it doesn't work, I'm not able to tell to filter how to understand if it's a new request or an old request expired. This is the code I used:
if (session.getAttribute("userProfile") == null) {
logger.debug("Session: " + ( session.isNew() ? "true" : "false"));
logger.debug(request.getSession().isNew());
if ( request.getRequestedSessionId() != null && !request.isRequestedSessionIdValid() ) {
return new ModelAndView("redirect:expired.htm");
} else {
return new ModelAndView("redirect:login.htm");
}
}
I tried different solutions proposed here on Stack Overflow and on the general internet, but nothing has worked and every request goes to expired.htm.
How do you get the session object? Before doing that, use
if (request.getSession(false)==null) {
// no session present (expired or new visitor)
[... do something ...]
} else {
// active session present
}
You need to use the validation above before use any attribute in the session. Because if the session don't exists you can't get an attribute of it.
You need to put false inside parentesis.
if(request.getSession(false) == null) { //Session don't exists
...
}
Java explain:
public HttpSession getSession(boolean create)
Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.
If create is false and the request has no valid HttpSession, this method returns null.
To make sure the session is properly maintained, you must call this method before the response is committed. If the container is using cookies to maintain session integrity and is asked to create a new session when the response is committed, an IllegalStateException is thrown.
Parameters:
create - true to create a new session for this request if necessary; false to return null if there's no current session
Returns:
the HttpSession associated with this request or null if create is false and the request has no valid session

creating login and welcomenpages using JSP

I want to create a login page thats when the user select either remember username or remember me check box, a cookie should be generated, when the remember username checkbox is selected, it should store the username, when the remember me checkbox is selected it should store both the username and password to avoid retyping whena user returns to the login page.
I wrote the preceeding code to incorporate the functionality but on testing the page the user has to retype the username each time the login page is loaded. I am not able to identify the cause of the problem, can someone help me with this?
<%
String userName = request.getParameter("username");
String password = request.getParameter("password");
String rm_me = request.getParameter("rm_me");
String rm_uname = request.getParameter("rm_uname");
if (userName != null && password != null) {
if (rm_me != null) {
Cookie ckU = new Cookie("username", userName);
Cookie ckP = new Cookie("password", password);
response.addCookie(ckP);
} else {
if (rm_uname != null) {
Cookie ckU = new Cookie("username", userName);
}
}
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals("username")) {
userName = cookies[i].getValue();
}
if (cookies[i].getName().equals("password")) {
password = cookies[i].getValue();
}
}
}
%>
You shouldn't be doing this kind of stuff in a JSP. You should use do it in a "controller" servlet and then forward the outcome to a JSP to (just) format the HTML response.
And I think your problem is most likely to be related to that. Specifically, I suspect that the response will already have been committed by the time that the scriptlet code executes. This means that your response.addCookie(...); call will be too late to add a SetCookie header to the response.
You should be able to confirm this by dumping the response headers when they leave the server or when they reach your browser ... or (less directly) by looking in the browser cookie store.
Pretty much any introductory book or tutorial on JSP would include examples of everything you want.
Any reasonably recent one will also tell you that using Java code in a JSP is very bad indeed, just don't do it.
Use JSTL instead.

How do I check for the null value in Java?

How to look for the value whether it is null or not in JSP. E.g. in below I want to check the description column in pipe table for null values.
String Query1 = "SELECT description FROM pipe where pipe_id='" + id+"' and version_id=2";
SQLResult = SQLStatement.executeQuery(Query1);
SQLResult.first();
description = SQLResult.getString("description");
if(description=="")
{
json_string=json_string+"&desc="+description;
out.println("not null");
} else
{
json_string=json_string;
out.println("null");
}
Well: if (description != null && !description.isEmpty()) ... however are you writing this code within a JSP ? That seems wrong. You should probably do this stuff within a servlet and pass the description as an request attribute to a jsp.
Or you can use StringUtils.isNotEmpty(description).
If you are really using jsp, you should store description in a request attribute and then use <c:if test="${empty description}">.
I use this personal method:
public static boolean isNullOrEmpty(Object obj) {
if (obj == null || obj.toString().length() < 1 || obj.toString().equals(""))
return true;
return false;
}

Categories