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
Related
Please i cheked for the answer of this question and i found this one : enter link description here
how can i do that using session:
request.setAttribute("attributeName",yourStringVAlue);
RequestDispatcher rd = request.getRequestDispatcher("yourServletPattern");
rd.forward(request,response);
and to retrieve :
String someName = (String)request.getAttribute("attributeName");
You stated "using session".
Set variable:
HttpSession session = request.getSession();
session.setAttribute("myId","myVariable");
Retrieve variable:
HttpSession session = request.getSession();
String var = (String) session.getAttribute("myId");
I have an issue, my whole JSF application is based on Ajax Requests
We do every request and everything using Ajax
The problem is when the session is timed out and the user tries to do anything on the page it just do nothing.
I know that the session is timed out but I wasn't able to catch it. after some trying finally I'm able to catch when the session is timed out after each request. but the problem now is to redirect the user to the login screen again from the filter or the managed bean or even using js
Please anyone can tell me what to do to redirect the user to the login screen
also please keep in mind that I have three pages in my application : login and index and logout only and everything is in the index page
Thanks in advance
you can use something like that in order to make an ajax redirection inside your timeout filter. You can refer to this thread
String facesRequestHeader = httpServletRequest
.getHeader( "Faces-Request" );
boolean isAjaxRequest = facesRequestHeader != null
&& facesRequestHeader.equals( "partial/ajax" );
if( isAjaxRequest )
{
String url = MessageFormat.format( "{0}://{1}:{2,number,####0}{3}",
request.getScheme(), request.getServerName(),
request.getServerPort(), timeoutPath );
PrintWriter pw = response.getWriter();
pw.println( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" );
pw.println( "<partial-response><redirect url=\"" + url
+ "\"></redirect></partial-response>" );
pw.flush(););
}
else
{
httpServletResponse.sendRedirect( timeoutPath );
}
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(""))
This question already has answers here:
How do I keep a user logged into my site for months?
(2 answers)
Closed 5 years ago.
I have a login screen and i am authenticating users by checking credentials from database. But how can i implement Remember me check box? Like in gmail remember me(stay signed in) is present. I am using sign.jsp and Auth servlet (doPost) and oracle 10g ee for authentication.
You can use cookies for this purpose.
In your servlet response handler (doPost, doGet etc.) create a cookie in the following way -
if(remember_me_is_checked)
{
Cookie c = new Cookie("userid", userId.toString());
c.setMaxAge(24*60*60);
response.addCookie(c); // response is an instance of type HttpServletReponse
}
To read them, you can use something like this -
Cookie[] cookies = request.getCookies(); // request is an instance of type
//HttpServletRequest
boolean foundCookie = false;
for(int i = 0; i < cookies.length; i++)
{
Cookie c = cookies[i];
if (c.getName().equals("userid"))
{
string userId= c.getValue();
foundCookie = true;
}
}
Here is the official documentation for the Cookie class.
You can use cookies to help with your implementation. Something like this .
String userIdendificationKey="UserName";
Cookie cookie = new Cookie ("userIdendificationKey",userIdendificationKey);
// Set the age of the cokkie
cookie.setMaxAge(365 * 24 * 60 * 60);
//Then add the cookies to the response
response.addCookie(cookie);
and then check against the particular value later .
I don't know whether it is secure or not,but this is what i did.
In login.jsp head tag
<script type="text/javascript">
var isLoggedIn = "${isLoggedIn}";
if(isLoggedIn === true)
window.location.href="Home.jsp";
</script>
in body tag i added a check box for Remember Me as below
<input type="checkbox" id="RememberMe" name="rememberMe">
<label for="RememberMe">Remember Me</label>
In servlet doPost method i added the code below
if(userdetails are verified)
{
if(request.getParameter("rememberMe")!=null){
request.getSession().setAttribute("isLoggedIn", true);
}
RequestDispatcher rs = request.getRequestDispatcher("Home.jsp");
rs.forward(request, response);
}
else
{
RequestDispatcher rs = request.getRequestDispatcher("fail.jsp");
rs.include(request, response);
}
using this it will ask for the credentials at first time login,and it will store the login info in session parameters,if you try to access the site second time it will automatically goes to "Home.jsp" instead of "login.jsp"
please comment whether this method is good practice,any other modifications can be done.
Suggestions are welcome.
Take a look at Spring SecurityIt
It is a powerful and highly customizable authentication and access-control framework.
You can also check the code from Rose India, this will be more helpful to you.
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.