Sessions automatically generating from servlet/jsp despite having condition : <%#page session="false" %> - java

I have given a session timeout of 1 minute in my application's web.xml :
<session-config>
<session-timeout>1</session-timeout>
</session-config>
I am also checking at each and every step whether the servlet or jsp is preventing auto generation of new session on its own.
e.g.
In each and every jsp file I am giving following sets of instructions to prevent autogeneration :
<%# page session="false"%>
<%#page isELIgnored="false" %>
And in the corresponding servlet of every jsp file, I am authenticating the session as follows :
RequestDispatcher dispatcher;
HttpSession httpSession = request.getSession(false);
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setDateHeader("Expires", 0); // Proxies.
if (httpSession == null) {
dispatcher = request.getRequestDispatcher("/WEB-INF/view/sessionexpire.jsp");
dispatcher.forward(request, response);
} else {
// collecting the parameters from front end...
Still it is auto generating a new session even at the expiry of current session.
I have written a debug statement in my application that checks for the flaw :
System.out.println("session id : " + httpSession.getId());
The above statement prints a new session id if the page is reloaded despite session expiration.
What I want, is that once the session gets expired, the corresponding page in my iframe should display the message of session expiration and user must be forced to relogin.
But what it does instead is that when i re-click on the link, it opens the same web page with a brand new session.
I have also placed a HttpSessionListener that does some cleaning job for me.
public class InsightHttpSessionListener implements HttpSessionListener {
#Override
public void sessionCreated(HttpSessionEvent arg0) {
}
#Override
public void sessionDestroyed(HttpSessionEvent arg0) {
InsightDbConn insightDbConn = InsightDbConn.getInstance();
HttpSession httpSession = arg0.getSession();
insightDbConn.getFeatureIds().clear();
System.out.println("feature ids list clear");
}
I really dont know what went wrong. Please explain where I am leaving the flaw and session is regenerating by its own.

Related

A JSP page creates a JSESSIONID cookie where not appropriate

When I visit my page .../index.jsp while having no HttpSessions, index.jsp still creates the JSESSIONID-cookie. Even worse, in the servlet responsible for logging people out, session.invalidate() does not seem to fix the issue.
index.jsp looks like this:
<%#page import="javax.servlet.http.Cookie"%>
<%#page contentType="text/html" pageEncoding="utf-8"%>
<%#page session="true"%>
<%!
void removeJSessionIdCookie(HttpServletResponse response) {
Cookie cookie = new Cookie("JESSIONID", "");
cookie.setValue(null);
cookie.setMaxAge(0);
cookie.setPath("/");
response.addCookie(cookie);
}
%>
<%
if (session != null) {
out.print("Session not null.");
if (session.getAttribute(Config.CURRENT_USER_ATTRIBUTE) != null) {
out.print("have user");
request.getRequestDispatcher("app.jsp").forward(request, response);
return;
} else {
out.println("no user here");
session.invalidate();
removeJSessionIdCookie(response);
}
}
%>
<html>...</html>
If you have session="true" in your <%#page%> directive, then the JSP framework code always creates a new session if the calling client does not bring a session cookie, i.e. has no session yet.
You need to put session="false" in to the page directive; this makes the Framework stop creating sessions for you.

The Java servlet HttpSession does not seem to work immediately

In my login servlet, the last code of doPost is as follows:
HttpSession session = request.getSession();
session.setAttribute(Config.CURRENT_USER_PARAMETER, user);
request.getRequestDispatcher("app.jsp").forward(request, response);
What comes to app.jsp, it is as follows:
<%#page import="fi.vakuutustiedot.controllers.Config"%>
<%#page import="fi.vakuutustiedot.model.User"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%
if (session == null) {
request.getRequestDispatcher("index.html").forward(request, response);
return;
}
User user = (User) session.getAttribute(Config.CURRENT_USER_PARAMETER);
if (user == null) {
session.invalidate();
request.getRequestDispatcher("index.html").forward(request, response);
return;
}
%>
<!DOCTYPE html>
...
My problem is the following scenario:
I login through the HTML form that is connected to my login servlet.
The login servlet creates a HttpSession and adds an attribute for the object describing the user in question.
Finally, it forwards to app.jsp.
The problem is that when I am logged and forwarded to app.jsp, I see everything I am supposed to see, but if I type .../app.jsp in the location bar and press Enter it redirects to index.html! However, when I visit app.jsp the second, third, .etc time, everything is fine and no spurious redirect to index.html happens.
Is this solution adequate from the security standpoint?
I resolved the issue by adding in the login servlet the following line:
HttpSession session = request.getSession();
request.setAttribute(Config.CURRENT_USER_PARAMETER, user); // <- The new added line.
session.setAttribute(Config.CURRENT_USER_PARAMETER, user);
request.getRequestDispatcher("app.jsp").forward(request, response);
And in app.jsp I have:
<%#page import="fi.vakuutustiedot.controllers.Config"%>
<%#page import="fi.vakuutustiedot.model.User"%>
<%#page import="fi.vakuutustiedot.model.UserType"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%! User user = null; %>
<%
if (session == null) {
request.getRequestDispatcher("no_session.html").forward(request, response);
return;
}
user = (User) session.getAttribute(Config.CURRENT_USER_PARAMETER);
if (user == null) {
user = (User) request.getAttribute(Config.CURRENT_USER_PARAMETER);
}
if (user == null) {
request.getRequestDispatcher("test.jsp").forward(request, response);
return;
}
%>
<!DOCTYPE html>
...
Answering my own question
In the login servlet, all I do is:
HttpSession session = request.getSession();
session.setAttribute(Config.CURRENT_USER_PARAMETER, user);
response.sendRedirect("app.jsp");
That way, the user object is available straight from the session and I do not need to put that user to the request object.
It would seem you are trying to get to a page outside of your context.
By your question, I am only guessing your directory is:
/index.html
/app.jsp
When you are running your application, you probably inter a URI such as:
http://[my_server]/[my_app]/index.html
or just:
http://[my_server]/[my_app]/
When you type ../app.jsp, your are trying to get something that is not there. Your server is probably set to send a default page of index.html with no default error page.
I am guessing you are just getting back the index.html page because of the incorrect URI.

How session gets create in JSP?

I am learning JSP. I am not able to find out how sessions got created in JSP.
what I know till now is session is implicit object creates under _jspService method. So I manually created session. In below JSP code I created session same as it automatically creates in index_jsp but i am getting value as null. So any body can explain me why I am getting null?
<%# page import ="java.util.*" session="false" %>
<%
javax.servlet.http.HttpSession session = null;
session = pageContext.getSession();
%>
<html>
<body>
<%=session %>
</body>
As you said:
session is implicit object created under _jspService method
The JSP file is compiled by the Jasper Engine to a java class. Despite of the code you have writen in the JSP, in the created Java class there are some preparation of these implicit objects.
Therefore you don't need to do it again.
You can just use them. You can write in your JSP the code:
From EL:<br>
sessionScope.name: ${sessionScope.name}<br>
<br>
From Scriptlet. <br>
<%=session.getAttribute("name")%>
And you get the same output twice: the value of the session attribute "name".
In example of a JSP with content:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Title</title>
</head>
<body>
From EL:<br>
sessionScope.name: ${sessionScope.name}<br>
<br>
From Scriptlet. <br>
<%=session.getAttribute("name")%>
</body>
</html>
Will result in a java class file:
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class testcompile_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List<String> _jspx_dependants;
private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector;
public java.util.List<String> getDependants() {
return _jspx_dependants;
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html; charset=UTF-8");
response.setHeader("X-Powered-By", "JSP/2.3");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\r\n");
out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\r\n");
out.write("<html>\r\n");
out.write("<head>\r\n");
out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n");
out.write("<title>Title</title>\r\n");
out.write("</head>\r\n");
out.write("<body>\r\n");
out.write("From EL:<br>\r\n");
out.write("sessionScope.name: ");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${sessionScope.name}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("<br>\r\n");
out.write("<br>\r\n");
out.write("From Scriptlet. <br>\r\n");
out.print(session.getAttribute("name"));
out.write("\r\n");
out.write("</body>\r\n");
out.write("</html>");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
As you can see in the _jspService method there are lines:
HttpSession session = null;
...
session = pageContext.getSession();
Basically this is the implicit session object. Your code follow after that and can use it.
EDIT:
With <%# pagesession="false" %> you say "i don't need the session". So the session is not bond in the pageContext. Therefore you if you call pageContext.getSession() you receive null;
If you need it you have to use:
request.getSession();
Can explain me why I am getting null for session ?
The session in the JSP file will be disabled if you set the session attribute to false i.e., session="false", you can look here for more details.
I am not able to find out how sessions got created in JSP.
httpsession object will be created (& maintained) by the servlet container when you invoke request.getSession(true); from JSP (because request is also an implicit object in JSP).
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.
You can refer the API here
So, to create the session from your code you change it as:
<%
javax.servlet.http.HttpSession session = request.getSession(true);
// you can session object from now add attributes,
// get attributes, remove attributes, etc..
%>
Also, once the session is created (as shown above using request.getSession(true)), you need to use request.getSession() to retrive the same session object.
In other words, in your whole application,
(1) Create the session ONLY ONCE during the user login time in LoginServlet or LoginController class using request.getSession(true)
(2) And then use request.getSession() in all other servlet/controller methods.
As a side note, I strongly suggest you to use Controller (like using Spring) or Servlet classes to write the Java code because JSP is meant only for the presentation layer (to display the html content).

Very random empty jsp form data on submit after validation

We have a jsp (2.2)/jstl(2.1) form that submits to a java servlet (3.0) on tomcat 7 server. Randomly, intermittently we will get a submission to the servlet with all the http request parameter values as null. Our form has some fields that are pre-populated so we expect at least those to be retrievable but they are null at the serlvet as well. Almost all of the form submissions we receive contain form data and are successfully processed. It's the once in every so many submissions that has the completely empty http request parameter set that I cannot figure out nor reproduce. There are no file uploads involved, the data is submitted via post. We validate client side and server side. I have searched high and low for reasons why the form data can be empty but have not had any success. Any thoughts?
1) no file uploads
2) all fields have 'name='
3) method is post
4) data is validated prior to submission
5) implement a filter for db entity management
partial jsp form:
<%# page contentType="text/html; charset=UTF-8" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%
response.setHeader("Cache-Control", "no-cache");//Forces caches to obtain a new copy of the page from the origin server
response.setHeader("Cache-Control", "no-store");//Directs caches not to store the page under any circumstance
response.setDateHeader("Expires", 0);//Causes the proxy cache to see the page as "stale"
response.setHeader("Pragma", "no-cache");//HTTP 1.0 backward enter code here
%>
<!DOCTYPE html>
<!--head/body stuff -->
<form id="app_form" name="app_form" action="process" method="post" novalidate="novalidate" accept-charset="ISO-8859-1">
<!-- general form fields using html/jstl -->
<button type="submit" id="submit_application" name="submit_application" class="submit application submitbtn" title="I'm finished and want to submit my completed application.">SUBMIT APPLICATION</button>
</form>
partial filter:
public class EntityManagerFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
log.debug("Initializing filter...");
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
EntityManagerUtil.getEntityManager().getTransaction().begin();
chain.doFilter(request, response);
EntityManagerUtil.getEntityManager().getTransaction().commit();
} catch (Throwable ex) {
}
partial java servlet:
public class ProcessApplicationFormServlet extends BaseServlet {
private static Logger log = Logger.getLogger(ProcessApplicationFormServlet.class);
private static final long serialVersionUID = 1L;
Application_Domestic appdata = null;
Domestic_user currentUser = null;
String sessID = null;
String program = null;
String type = null;
#Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
//values from form
appdata.setTitle(maxLength(req.getParameter("title"),25));
appdata.setFirst(maxLength(req.getParameter("first"),30));
appdata.setMiddle(maxLength(req.getParameter("middle"),30));
appdata.setLast(maxLength(req.getParameter("last"),57));
appdata.setSuffix(maxLength(req.getParameter("suffix"),25));
appdata.setEmail_Address(maxLength(req.getParameter("trueemail"),50));
etc...
process data
}
}
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
These are just the portions that deal with submission/http request. If there are other important coding considerations that I need to show, please let me know. Do keep in mind that only 1 - 2 percent of the form submissions come in with empty httpServletRequest data. This code has been tested and working. I just cannot seem to be able to reproduce the scenario when a user submits the form (it can not be submitted until all data as been validated) and it reaches the servlet with an empty data set where every parameter is null.

Session attribute is null at first load

I have the following servlet:
#WebServlet(name = "Placeholder",urlPatterns = {"/foo"})
public class Placeholder extends HttpServlet {
public static int numbers=5;
HttpSession session;
public void doGet (HttpServletRequest _req, HttpServletResponse _res) throws ServletException, IOException {
/* Refresh session attributes */
session = _req.getSession();
session.setAttribute("wee","ok");
}
}
With the following JSP:
<%#page language="java" contentType="text/html"%>
<%#page import="java.util.*, java.io.*"%>
<%#page import="main.java.Placeholder.*" %>
<html>
<body>
<b><% out.println("wee, printing from java");%></b>
<% out.println("<br/>Your IP address is " + request.getRemoteAddr());
String value = (String) session.getAttribute("wee");
out.println(value);%>
</body>
</html>
I'm surely missing the point somewhere as attribute wee is resolved as null, first time I load the page. If I go to /foo I get empty an page, and after I get back and reload the root page of servlet, wee actually gets its value.
My goal here is to simply print variables from the servlet into the view, no routing needed. Not sure that urlPatterns are needed here, but it does not work for now without this little hack.
UPD. Ok, so I've figured out that whatever route I put in, I need to add some characters in browser, get back and reload the page.
So, the root is 0.0.0.0:8080/webapp
I need to access,say 0.0.0.0:8080/webapp/qwerty , get back to /webapp and refresh the page.
How do I get session instantiated by just going to /webapp?
Why don't I have 404 or 500 on accessing some random unexisting route /webapp/randomstuff?
First configure servlet as welcome file in web.xml. If web.xml not present than create it manually inside WEB-INF folder and put below content inside it.
<welcome-file-list>
<welcome-file>foo</welcome-file>
</welcome-file-list>
than in your servlet dispatch request to your jsp lets say your jsp name is index.jsp than your servlet code would be look like:
#WebServlet(name = "Placeholder",urlPatterns = {"/foo"})
public class Placeholder extends HttpServlet {
public static int numbers=5;
public void doGet (HttpServletRequest _req, HttpServletResponse _res) throws ServletException, IOException {
HttpSession session = _req.getSession();
session.setAttribute("wee","ok");
_res.sendRedirect("index.jsp");
}
}
Now run your servlet you will see output.
Hope this solve your problem!!!

Categories