How do you persist a tomcat session? - java

i have a JSP web page that refreshes every 1 minute.
on each refresh, the session object is checked for validity.
When the tomcat web server restarts, the session goes away...and when the page refreshes, it says "invalid". anyone has a solution to my problem?

Have a look at the configuration in your Tomcat config file. The documentation is at http://tomcat.apache.org/tomcat-6.0-doc/config/manager.html Look for the section on persistent managers ...

You have to make sure that ALL your objects your store in your Session are Serializable. If one of them isn't (or doesn't meet the Serializable requirements) you will lose your session on web app reload or tomcat restart.
EG: The following works fine for a Servlet:
public class MainServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
HttpSession session = request.getSession();
Date date = (Date) session.getAttribute("date");
if (date == null) {
date = new Date();
session.setAttribute("date", date);
}
response.setContentType("text/plain");
PrintWriter pw = response.getWriter();
pw.println("New Session? " + session.isNew());
pw.println("Date : " + date);
pw.flush();
}
}

Related

Losing Session on POST

I have been trying to find the reason as to why my session would be lost when I do a POST.
I am checking my session all throughout my app but the session will drop when I call a particular servlet and it only drops on this particular one. The issue is intermittent so it is very frustrating. I'm not sure what is needed so I'll put as much info as I can up.
The page is accessed through a servlet. I can verify that the session is still the same.
As the user is routing through the app, I can see that the session is still the same.
Checking Session:HTTP Session CEHKIIMEKHMH
Calling Get Details
Checking Session:HTTP Session CEHKIIMEKHMH
Calling Project Details
Checking Session:HTTP Session CEHKIIMEKHMH
Calling Attachment Controller
Checking Session:HTTP Session CEHKIIMEKHMH
public class Attachments extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Calling Attachment Controller");
HttpSession session = request.getSession(false);
System.out.println("Checking Session:"+session);
if(session != null){
Object projectId = session.getAttribute("projectId");
request.getRequestDispatcher(response.encodeURL("views/attachments.jsp")).forward(request, response);
}else{
System.err.println("Invalid session");
response.sendRedirect("/");
}
}
}
Here is my form posting. The form is actually submitted via javascript after I perform validation, I just merely call $('#files).submit(); not sure if that really matters or not.
<form id="files" name="files" method="POST" action="FileUpload" enctype="multipart/form-data">
The moment they post, the session is lost
Calling File Upload
Checking Session:null
null
Here is the start of the servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Calling File Upload");
HttpSession session = request.getSession(false);
System.out.println("Checking Session:"+session);
if(session != null){
Object projectId = session.getAttribute("projectId");
System.out.println("Accessing File Upload: Session is valid");
It's the same method all across the board. I have no idea what the problem is.
I've narrowed down the issue but I still have not resolved it yet. It happens during my redirect. I also was not encoding the URL correctly. I have modified all my redirects to have the folowing:
request.getRequestDispatcher(response.encodeRedirectURL("views/attachments.jsp")).forward(request, response);
This only resolves it on the server side though and does not provide a solution when I am handling redirects from the client.

How to check in servlet that is an user new with session?

I am very new to java servlet programming. I have been writing a simple program for practicing java session. There are two .jsp file. first one called index.jsp, and another one is selection.jsp. And there is a servlet called controller. At first the index.jsp will be called, and user will be submit a input. That will be redirect in servlet controller. In that servlet will check whether it is new request or not. If new then it redirect to other page, else will do some other work.
I am checking whether it is new request or not by session.isNew() method. But it always says it is not new session. But, if I disable the browser cookies option then it is working fine. Now what is my observation is that when in the first I request the index.jsp to the container it assign a session along with that request. So when it comes to servlet it treat as a old session. I got this idea from Head first book Servlet and JSP.
Here is my servlet code -
public class Controller extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user;
HttpSession session = request.getSession(false);
if (session == null) {
user = request.getParameter("user");
if (user == null) {
response.sendRedirect("index.jsp");
}
session.setAttribute("username", user);
SelectItem selectItem = new SelectItem();
selectItem.setUser(user);
response.sendRedirect("selection.jsp");
session.setAttribute("selectItem", selectItem);
} else {
String selectionItem = request.getParameter("selection");
SelectItem selectItem = (SelectItem) session.getAttribute("selectItem");
if (selectItem != null) {
selectItem.add(selectionItem);
session.setAttribute("selectItem", selectItem);
}
response.sendRedirect("selection.jsp");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
So, how to determine whether it is a new session or old one? Thank you.
HttpSession.isNew API:
Returns true if the client does not yet know about the session or if the client chooses not to join the session. For example, if the server used only cookie-based sessions, and the client had disabled the use of cookies, then a session would be new on each request.
So, you're getting true because the client has cookies disabled. The "new session" check in done in the else block of this check:
HttpSession session = request.getSession(false);
if (session == null) {
// create new session
session = request.getSession();
} else {
// existing session so don't create
}
In your code, you don't appear to be creating a new session when a new session is detected. Perhaps that's where you're stumbling.
Note: learning the basic Servlet API is a good thing. However, for my professional work I use frameworks which simplify my programming, like Spring Boot and Spring Security.

HTPPSession with Google Cloud Endpoints new session every time

I am successfully using Google Cloud Endpoints. Now for custom user auth, I want to use HTTPSession. The problem is, the initial session is not being reused in future calls, and new session are created (I can see from datastore admin that the session all exists, _AH_SESSION entity). As instructed in the docs, i have enabled it in appengine-web.xml:
<sessions-enabled>true</sessions-enabled>
I made some sample code to narrow it down:
#Api(name = "loginService", version = "v0.1.5")
public class LoginService {
private static final Logger log = Logger.getLogger(LoginService.class.getName());
#ApiMethod(name = "login", path= "login")
public LoginResponse login(HttpServletRequest req)
{
HttpSession session = req.getSession(false);
if(session == null){
log.warning("creating new session");
session = req.getSession(true);
}
LoginResponse resp = new LoginResponse();
resp.statusCode = 200;
resp.statusMessage = "SessionId:" + session.getId();
return resp;
}
#ApiMethod(name = "show", path= "show")
public LoginResponse show(HttpServletRequest req)
{
//session should exist when calling LOGIN first
HttpSession session = req.getSession(false); //NULLPOINTER since session from login is not being reused/found!
LoginResponse resp = new LoginResponse();
resp.statusCode = 200;
resp.statusMessage = "SessionId:" + session.getId();
return resp;
}
public class LoginResponse implements Serializable{
public int statusCode;
public String statusMessage;
}
}`
So first, I call the login method, this creates a new session and prints me the session id. Then in the next request (both using Postman - which should track sessions - in Chrome as the API explorer) i call the 'show' endpoint, and there the previous session does not exist anymore, hence the nullpointer exception.
In the comments on this post, user mikO says endpoints don't keep the session. Is this the reason? I don't really understand the reason behind it. When I just deploy a 'regular' servlet on appengine, it DOES work using Postman or just browsing.. (testing by calling the getter twice, i see that the previous session is being picked up), so it seems that the comment in that post could be right, but i really don't understand why. Working code without endpoints:
public class LoginServlet extends HttpServlet {
private static final Logger log = Logger.getLogger(LoginServlet.class.getName());
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
HttpSession s = request.getSession(false);
if (s == null) {
log.warning("creating new session");
s = request.getSession(true);
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>" + s.getId() + "</h1>");
}
}
Thanks!

changing URL but want to send data to controller

My web application has a new requirement that if parameter coming in url then land to email page. otherwise on index page like always.
Its a very old client product and not much scope to change lot in code so i put a check in controller that if encrypted email coming in then land to email page.
example url -
http://localhost:8080/R2/Controller?email=jAOtTv22BfkTkVrhTN/RHQ==
Everything works fine but i want to change URL.
How can i get rid of " /Controller " in URL but still it hits to controller.???
Controller code like -
public class Controller extends HttpServlet {
static Logger logger = Logger.getLogger(Controller.class);
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
// get the action property from the request
String theAction = request.getParameter("action");
String theSource = request.getParameter("s");
String theSource1 = request.getParameter("email");
String em ="";
Action action=null;
em = EncryptEmail.decrypt(theSource1,GFWConstants.BLOWFISH_KEY);
if (em.equals(""))
rd = request.getRequestDispatcher("index.jsp?emailRtv=0");
else
rd = request.getRequestDispatcher("email-preferences.jsp?emailRtv=2&emailAddress="+em);
rd.forward(request,response);
return;
}
Thanks in advance.
adding two url-pattern to web.xml file worked.

Declare a session variable golbaly to access from DoGet and DoPost in a sevlet

I have a servlet where I need to declare a session which can be acceptable form doGet and doPost both how I should do this?
I have done
#WebServlet(name = "LoginLogout", urlPatterns = {"/LoginLogout.do"})public class LoginLogout extends HttpServlet {//For Session
HttpSession session = request.getSession(true);
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String status = request.getParameter("status");
System.out.println(status);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String loginId = request.getParameter("login_id");
String password = request.getParameter("password");
System.out.println(loginId);
//Inserting value to the Pogo named "newLoginPogo"
loginData newLoginPogo = new loginData();
newLoginPogo.setLoginId(loginId);
newLoginPogo.setPassword(password);
//Creating a obj of ModelLogin to send the loginId and Password via a method which is in ModelLogin class
ModelLogin loginBis = new ModelLogin();
loginData userData = loginBis.checkUser(newLoginPogo);
String userExist = userData.getUserExist();
System.out.println(userExist);
if ("yes".equals(userExist)) {
System.out.println("In while loop of Servlet");
String firstName = userData.getFirstName();
String userId = userData.getUserId();
boolean IsSu = userData.getIsSu();
//conveting boolean to string
String superuser = new Boolean(IsSu).toString();
//Creating a session
session.setAttribute("firstName", firstName);
session.setAttribute(userId, "userId");
session.setAttribute(superuser, "IsSu");
//==============================================================================================================
//If user does exist show the Success Message and forward Dashboard
//==============================================================================================================
//Session for success message
String succmsg = "Login Successful";
session.setAttribute("succmsg", succmsg);
getServletConfig().getServletContext().getRequestDispatcher("/WEB-INF/ViewPages/dashboard/dashboard.jsp").forward(request, response);
} //==============================================================================================================
//If user does not exist show the Error Message
//==============================================================================================================
else if ("no".equals(userExist)) {
//Session for success message
System.out.println("inside NO");
String emsg = "Login Error";
session.setAttribute("errmsg", emsg);
getServletConfig().getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
} else {
}
/*
//===============================================================================================================
//code for Logout
//===============================================================================================================
String status = request.getParameter("status");
if ("logout".equals(status)) {
//clearing the session
session.invalidate();
//forwarding to index page
getServletConfig().getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
}
*/
} finally {
}
}}
But it says
Can Not find Symbol
in this line HttpSession session = request.getSession(true);
You don't need to have session variable in servlet as field. In general - this is kind of common mistake. There will be only one onstance of servlet serving lots of requests, and unless you declare it as single-threaded - the requests would be handled concurrently.
HttpSession will be pre-exist for you in doGet and doPost via request object. Servlet container will guarantee this. So simply obtain reference to the session in doGet/doPost and do whatever you want.
What you desire is one of the roles of HTTP session.
You can look at it as a conversation between the client and the server.
As long as the "conversation" (HTTP session) is open and alive, you can set variables on the HTTP session, and access them from different requests that will sent on the same session.
Look at this as some sort of "shared memory" that exists during the "conversation time".
You can find many examples on how to do that over the internet.
Here is an example for session tracking.

Categories