Java IE Gives Old HTTP Servlet Session Object - java

I am using IE 11 for my application. i am facing session issue here.
When doing first transaction, in transaction response jsp page i get current transaction no say 1000 [(TransactionDO) session.getAttribute("txnDetails");].
In same jsp i did ng-init="GetTxnResponse()" in div, from that js function getting transaction no as 1000.
then i am doing second transaction with the same session without logout, in transaction response jsp page i get current transaction no as 1001 from http session.
In same jsp from ng-init="GetTxnResponse()" js function getting transaction no as 1000 instead of 1001.
Its occurs only in IE. Please help to resolve. Below is my code for reference.
-- JSP Code --
<fmt:setLocale value='en_US' />
<%
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
// HTTP 1.1.
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
TransactionDO txnDO = (TransactionDO) session.getAttribute("txnDetails");
System.out.println("Txn no : "+txnDO.txnNo()); // Here i get 1001 second time
%>
<fmt:bundle basename="applicationresources">
<div ng-controller="txnController"
ng-init="GetTxnResponse()" >
---
---
</div>
</fmt:bundle>
-- JS Code --
self.GetTxnResponse = function() {
if (txnStatus == '00') {
$http.get(CONTEXT_PATH + '/getResponseDetails').success(function(data) {
// Here i get 1000 from data second time
}
}
-- Java Code --
#RequestMapping(value="/getResponseDetails", method=RequestMethod.GET)
public #ResponseBody TransactionDO getResponseDetails(HttpServletRequest httpRequest){
TransactionDO txnDO = null;
txnDO = (TransactionDO) httpRequest.getSession().getAttribute("txnDetails");
return txnDO;
}

Make the page stateless. That is solid practice. It also allows caching on the production site.
<div ng-controller="txnController"
ng-init="GetTxnResponse(${txnDetails.txnNo})" >
self.GetTxnResponse = function(txnNo) {
if (txnStatus == '00') {
$http.get(CONTEXT_PATH + '/getResponseDetails/' + txnNo).success(function(data) {
// Here i get 1000 from data second time
#RequestMapping(value="/getResponseDetails/{txnNo}", method=RequestMethod.GET)
public #ResponseBody TransactionDO getResponseDetails(HttpServletRequest httpRequest,
#PathVariable long txnNo) {
...
}
You need probably to adapt the page a bit more than the code shown.
To explain it a bit more: the user could open two tabs with the same page, and then play around. Guess what?

Related

Servlet with java.lang.IllegalStateException: Cannot forward after response has been committed [Apache POI] when export to Excel [duplicate]

This method throws
java.lang.IllegalStateException: Cannot forward after response has been committed
and I am unable to spot the problem. Any help?
int noOfRows = Integer.parseInt(request.getParameter("noOfRows"));
String chkboxVal = "";
// String FormatId=null;
Vector vRow = new Vector();
Vector vRow1 = new Vector();
String GroupId = "";
String GroupDesc = "";
for (int i = 0; i < noOfRows; i++) {
if ((request.getParameter("chk_select" + i)) == null) {
chkboxVal = "notticked";
} else {
chkboxVal = request.getParameter("chk_select" + i);
if (chkboxVal.equals("ticked")) {
fwdurl = "true";
Statement st1 = con.createStatement();
GroupId = request.getParameter("GroupId" + i);
GroupDesc = request.getParameter("GroupDesc" + i);
ResultSet rs1 = st1
.executeQuery("select FileId,Description from cs2k_Files "
+ " where FileId like 'M%' and co_code = "
+ ccode);
ResultSetMetaData rsm = rs1.getMetaData();
int cCount = rsm.getColumnCount();
while (rs1.next()) {
Vector vCol1 = new Vector();
for (int j = 1; j <= cCount; j++) {
vCol1.addElement(rs1.getObject(j));
}
vRow.addElement(vCol1);
}
rs1 = st1
.executeQuery("select FileId,NotAllowed from cs2kGroupSub "
+ " where FileId like 'M%' and GroupId = '"
+ GroupId + "'" + " and co_code = " + ccode);
rsm = rs1.getMetaData();
cCount = rsm.getColumnCount();
while (rs1.next()) {
Vector vCol2 = new Vector();
for (int j = 1; j <= cCount; j++) {
vCol2.addElement(rs1.getObject(j));
}
vRow1.addElement(vCol2);
}
// throw new Exception("test");
break;
}
}
}
if (fwdurl.equals("true")) {
// throw new Exception("test");
// response.sendRedirect("cs2k_GroupCopiedUpdt.jsp") ;
request.setAttribute("GroupId", GroupId);
request.setAttribute("GroupDesc", GroupDesc);
request.setAttribute("vRow", vRow);
request.setAttribute("vRow1", vRow1);
getServletConfig().getServletContext().getRequestDispatcher(
"/GroupCopiedUpdt.jsp").forward(request, response);
}
forward/sendRedirect/sendError do NOT exit the method!
A common misunderstanding among starters is that they think that the call of a forward(), sendRedirect(), or sendError() would magically exit and "jump" out of the method block, hereby ignoring the remnant of the code. For example:
protected void doXxx() {
if (someCondition) {
sendRedirect();
}
forward(); // This is STILL invoked when someCondition is true!
}
This is thus actually not true. They do certainly not behave differently than any other Java methods (expect of System#exit() of course). When the someCondition in above example is true and you're thus calling forward() after sendRedirect() or sendError() on the same request/response, then the chance is big that you will get the exception:
java.lang.IllegalStateException: Cannot forward after response has been committed
If the if statement calls a forward() and you're afterwards calling sendRedirect() or sendError(), then below exception will be thrown:
java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed
To fix this, you need either to add a return; statement afterwards
protected void doXxx() {
if (someCondition) {
sendRedirect();
return;
}
forward();
}
... or to introduce an else block.
protected void doXxx() {
if (someCondition) {
sendRedirect();
}
else {
forward();
}
}
To naildown the root cause in your code, just search for any line which calls a forward(), sendRedirect() or sendError() without exiting the method block or skipping the remnant of the code. This can be inside the same servlet before the particular code line, but also in any servlet or filter which was been called before the particular servlet.
In case of sendError(), if your sole purpose is to set the response status, use setStatus() instead.
Do not write any string before forward/sendRedirect/sendError
Another probable cause is that the servlet writes to the response while a forward() will be called, or has been called in the very same method.
protected void doXxx() {
out.write("<p>some html</p>");
// ...
forward(); // Fail!
}
The response buffer size defaults in most server to 2KB, so if you write more than 2KB to it, then it will be committed and forward() will fail the same way:
java.lang.IllegalStateException: Cannot forward after response has been committed
Solution is obvious, just don't write to the response in the servlet. That's the responsibility of the JSP. You just set a request attribute like so request.setAttribute("data", "some string") and then print it in JSP like so ${data}. See also our Servlets wiki page to learn how to use Servlets the right way.
Do not write any file before forward/sendRedirect/sendError
Another probable cause is that the servlet writes a file download to the response after which e.g. a forward() is called.
protected void doXxx() {
out.write(bytes);
// ...
forward(); // Fail!
}
This is technically not possible. You need to remove the forward() call. The enduser will stay on the currently opened page. If you actually intend to change the page after a file download, then you need to move the file download logic to page load of the target page. Basically: first create a temporary file on disk using the way mentioned in this answer How to save generated file temporarily in servlet based web application, then send a redirect with the file name/identifier as request param, and in the target page conditionally print based on the presence of that request param a <script>window.location='...';</script> which immediately downloads the temporary file via one of the ways mentioned in this answer Simplest way to serve static data from outside the application server in a Java web application.
Do not call forward/sendRedirect/sendError in JSP
Yet another probable cause is that the forward(), sendRedirect() or sendError() methods are invoked via Java code embedded in a JSP file in form of old fashioned way <% scriptlets %>, a practice which was officially discouraged since 2003. For example:
<!DOCTYPE html>
<html lang="en">
<head>
...
</head>
<body>
...
<% sendRedirect(); %>
...
</body>
</html>
The problem here is that JSP internally immediately writes template text (i.e. HTML code) via out.write("<!DOCTYPE html> ... etc ...") as soon as it's encountered. This is thus essentially the same problem as explained in previous section.
Solution is obvious, just don't write Java code in a JSP file. That's the responsibility of a normal Java class such as a Servlet or a Filter. See also our Servlets wiki page to learn how to use Servlets the right way.
See also:
What exactly does "Response already committed" mean? How to handle exceptions then?
Unrelated to your concrete problem, your JDBC code is leaking resources. Fix that as well. For hints, see also How often should Connection, Statement and ResultSet be closed in JDBC?
even adding a return statement brings up this exception, for which only solution is this code:
if(!response.isCommitted())
// Place another redirection
Typically you see this error after you have already done a redirect and then try to output some more data to the output stream. In the cases where I have seen this in the past, it is often one of the filters that is trying to redirect the page, and then still forwards through to the servlet. I cannot see anything immediately wrong with the servlet, so you might want to try having a look at any filters that you have in place as well.
Edit: Some more help in diagnosing the problem…
The first step to diagnosing this problem is to ascertain exactly where the exception is being thrown. We are assuming that it is being thrown by the line
getServletConfig().getServletContext()
.getRequestDispatcher("/GroupCopiedUpdt.jsp")
.forward(request, response);
But you might find that it is being thrown later in the code, where you are trying to output to the output stream after you have tried to do the forward. If it is coming from the above line, then it means that somewhere before this line you have either:
output data to the output stream, or
done another redirect beforehand.
Good luck!
You should add return statement while you are forwarding or redirecting the flow.
Example:
if forwardind,
request.getRequestDispatcher("/abs.jsp").forward(request, response);
return;
if redirecting,
response.sendRedirect(roundTripURI);
return;
This is because your servlet is trying to access a request object which is no more exist..
A servlet's forward or include statement does not stop execution of method block. It continues to the end of method block or first return statement just like any other java method.
The best way to resolve this problem just set the page (where you suppose to forward the request) dynamically according your logic. That is:
protected void doPost(request , response){
String returnPage="default.jsp";
if(condition1){
returnPage="page1.jsp";
}
if(condition2){
returnPage="page2.jsp";
}
request.getRequestDispatcher(returnPage).forward(request,response); //at last line
}
and do the forward only once at last line...
you can also fix this problem using return statement after each forward() or put each forward() in if...else block
I removed
super.service(req, res);
Then it worked fine for me
Bump...
I just had the same error. I noticed that I was invoking super.doPost(request, response); when overriding the doPost() method as well as explicitly invoking the superclass constructor
public ScheduleServlet() {
super();
// TODO Auto-generated constructor stub
}
As soon as I commented out the super.doPost(request, response); from within doPost() statement it worked perfectly...
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//super.doPost(request, response);
// More code here...
}
Needless to say, I need to re-read on super() best practices :p
After return forward method you can simply do this:
return null;
It will break the current scope.
If you see this on a Spring based web application, make sure you have your method annotated with #ResponseBody or the controller annotated with #RestController instead of #Controller. It will also throw this exception if a method returns JSON, but has not been configured to have that as the response, Spring will instead look for a jsp page to render and throw this exception.

Avoid session time out in Spring MVC

I pass all the necessary data using session variable and when session expires all the data will be lost. I want it not to expire on a particular jsp but when in other jsps session it can expire.
I propose sending a request to the server continuously according to the timer to avoid the session expiry in particular jsp.
I use spring mvc. How can I do this on particular jsp?
I tried below code but I need to do is send a request to the server without using image:
function keepMeAlive(imgName) {
myImg = document.getElementById(imgName);
if (myImg) myImg.src = myImg.src.replace(/?.*$/, '?' + Math.random());
}
window.setInterval("keepMeAlive('keepAliveIMG')", 100000);
<img id="keepAliveIMG" width="1" height="1" src="http://www.some.url/someimg.gif?" />
Try using ajax calls:
function keepAlive(){
$.get( window.location.pathname, function( data ) {console.log(data)} );
}
window.setInterval(keepAlive, 100000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
function f(){
var oRequest = new XMLHttpRequest();
var sURL = "http://"
+ "localhost:8080/sessionAlivecheck/"
+ "/example/newjsp.jsp";
oRequest.open("GET",sURL,false);
oRequest.setRequestHeader("User-Agent",navigator.userAgent);
oRequest.send(null);
//alert("hhh");
}
$(document).ready(function () {
setInterval(f, 2000);
});

send values from javascript page to servlet page at run-time

My_javascript_page
window.onload = loadResTimeData;
function loadResTimData() {
var e = window.performance.getEntriesByType("resource");
if (window.console) {
console.log("Resource Timming");
var perf_data = "";
var name, load, connection, request, fetch;
for (var i in e) {
if (e[i].name == "document") {
continue;
}
name = e[i].name.replace(/^.*\/|\.$/g, '') + ":";
load = e[i].duration;
request = e[i].responseEnd - e[i].requestStart;
fetch = e[i].responseEnd - e[i].fetchStart;
var s1={"Name": name, "CONNECTION":connection, "REQUEST":request, "LOAD":load, "FETCH":fetch};
var String1=JSON.stringify(s1);
console.log("Resource:" + name);
console.log("User Time:" + load);
console.log("Connection:" + connection);
console.log("Request Time:" + request);
console.log("Fetch Time:" + fetch);
$.ajax({
type:"POST",
url:"Final", //Final is my servlet page
data:String1,
datatype: "json"
});
}
}
}
}
This code calculates different response times when a web page is loaded and sends the data back to the servlet page.
This data i am printing on console(Console.log values), I want to send it to my servlet page in json format.
I tried doing it using jquery ajax, but the value didnot get passed to my servlet page.
Now I came accross various links where many people gave example on how to do it. But problem is
that all examples will be trigerred by clicking on the button. For that i need a form or may be some other thing
But in my application I want the data to be passed to my servlet page once the window.onload function is
trigerred; where I dont need a form or textfield. Also please let me know what exactly do i need to call at my server end(request.getparameter(???))
I am sharing the links i referred.
http://www.mysamplecode.com/2012/04/jquery-ajax-request-response-java.html
http://www.javacodegeeks.com/2014/09/jquery-ajax-servlets-integration-building-a-complete-application.html
JSP_page
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>JSP Page</title>
</head>
<body>
<script language='JavaScript'>
onclick=' window.onload';
Also I had people telling me to use cookies. I created cookies but my servlet page was not able to read it.
Someone suggested I can use hidden fields as well.
You can understand I am a mess right now. Please help as to where am I going wrong or what do i need to do now....

How to prevent client from accessing JSP page

In my web application, I use the .load() function in JQuery, to load some JSP pages inside a DIV.
$("#myDiv").load("chat.jsp");
In chat.jsp, no Java codes is executed unless this client has Logged in, means, I check the session.
String sessionId = session.getAttribute("SessionId");
if(sessionId.equals("100")){
//execute codes
}else{
//redirect to log in page
}
Those java codes that will be executed, they will out.println(); some HTML elements.
I don't want the client to write /chat.jsp in the browser to access this page, as it will look bad, and the other stuff in the main page won't be there, and this could do a harm to the web app security.
How can I restrict someone from accessing chat.jsp directly, but yet keep it accessible via .load() ?
UPDATE:
JavaDB is a class that I made, it connects me to the Database.
This is chat.jsp
<body>
<%
String userId = session.getAttribute("SessionId").toString();
if (userId != null) {
String roomId = request.getParameter("roomId");
String lastMessageId = request.getParameter("lastMessageId");
JavaDB myJavaDB = new JavaDB();
myJavaDB.Connect("Chat", "chat", "chat");
Connection conn = myJavaDB.getMyConnection();
Statement stmt = conn.createStatement();
String lastId = "";
int fi = 0;
ResultSet rset = stmt.executeQuery("select message,message_id,first_name,last_name from users u,messages m where u.user_id=m.user_id and m.message_id>" + lastMessageId + " and room_id=" + roomId + " order by m.message_id asc");
while (rset.next()) {
fi = 1;
lastId = rset.getString(2);
%>
<div class="message">
<div class="messageSender">
<%=rset.getString(3) + " " + rset.getString(4)%>
</div>
<div class="messageContents">
<%=rset.getString(1)%>
</div>
</div>
<% }
%>
<div class="lastId">
<% if (fi == 1) {%>
<%=lastId%>
<% } else {%>
<%=lastMessageId%>
<% }%></div>
<% if (fi == 1) {%>
<div class="messages">
</div>
<% }
} else {
response.sendRedirect("index.jsp");
}%>
</body>
Guys I don't know what Filter means.
UPDATE
If I decided to send a parameter that tells me that this request came from Jquery.
.load("chat.jsp", { jquery : "yes" });
And then check it in chat.jsp
String yesOrNo = request.getParameter("jquery");
Then they can simply hack this by using this URL.
/chat.jsp?jquery=yes
or something like that..
UPDATE
I tried Maksim's advice, I got this when I tried to access chat.jsp.
Is this the desired effect?
In order to achieve this in my application I check for X-Requested-With field in http header the client sends to my page in its request. If its value is XMLHttpRequest, then it's very likely that it came from an ajax request (jQuery appends this header to its requests), otherwise I don't serve the page. Regular (direct) browser requests will leave this header field blank.
In ASP.Net it looks like this, you will have to change your code slightly for JSP:
if (Request.Headers["X-Requested-With"] != "XMLHttpRequest")
{
Response.Write("AJAX Request only.");
Response.End();
return;
}
UPD: After quick googling your code will probably be something like this
if(!request.getHeader("X-Requested-With").equals("XMLHttpRequest")){
out.println("AJAX Request only.");
out.flush();
out.close();
return;
}
UPD2: Looks like request.getHeader("X-Requested-With") returns null in your case change the condition to something like this:
String ajaxRequest = request.getHeader("X-Requested-With");
if(ajaxRequest == null || !ajaxRequest.equals("XMLHttpRequest")){
...
}
Is your code snippet a servlet? If that's so, use a security framework (such as Spring Security) or a javax.servlet.Filter for applying security, then you can apply security to JSPs too.
you should use Filter. Check session in filter code and redirect to login.
according to http://www.c-sharpcorner.com/blogs/2918/how-to-set-a-request-header-in-a-jquery-ajax-call.aspx
JQuery gives you the tools you need to create a request and retrieve a response through it's ajax library. The raw $.ajax call gives you all kinds of callbacks to manipulate http messages.
So you can add a custom request header in your Ajaxa call like this
$.ajax({
type:"POST",
beforeSend: function (request)
{
request.setRequestHeader("Authority", "AJAXREQUEST");
},
...........
And then in your servlet check to see if the request has the header Authority equals to AJAXREQUEST. This is how you read request headers http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Request-Headers.html

Remember me in jsp login page [duplicate]

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.

Categories