JSP Automatic Refresh Retain Scrollbar Problem

Basically

I have a table that is inside a Div and the table gets filled out with data retrieved from the server. In order for the data to be up to date the Div has to be refreshed every 10 seconds or so. When viewing the table I will have to scroll down but with the 10 second refresh the scrollbar gets reset to the top of the table.

I have been told to implement ajax and also the use of cookies but my knowledge of Ajax and Javascript is limited .

Can anyone point me to an easy to understand solution? Like where to put the javascripts.

(I have also tried creating the table on a seperate JSP page and then putting this page in an IFrame in the main Page so that the table page refreshes but the main one does not. But I still have to problem with the scrollbar not retaining its position after refresh. )

[841 byte] By [ktsystemteq] at [2007-11-26 12:17:56]
# 1

> Basically

>

> I have a table that is inside a Div and the table

> gets filled out with data retrieved from the server.

> In order for the data to be up to date the Div has

> to be refreshed every 10 seconds or so. When

> viewing the table I will have to scroll down but

> with the 10 second refresh the scrollbar gets reset

> to the top of the table.

>

> I have been told to implement ajax and also the use

> of cookies but my knowledge of Ajax and Javascript is

> limited .

>

> Can anyone point me to an easy to understand

> solution? Like where to put the javascripts.

>

Not possible (I mean to give 'easy to understand solution'). You will have to learn Javascript and AJAX for this. Your page will be little more than style sheets to format the page, javascript to fill in the page and HTTPRequest calls to get the data. (or the alternative IFRAME with META-REFRESH and javascript to transfer data from the IFRAME to the main window).

> (I have also tried creating the table on a seperate

> JSP page and then putting this page in an IFrame in

> the main Page so that the table page refreshes but

> the main one does not. But I still have to problem

> with the scrollbar not retaining its position after

> refresh. )

stevejluke at 2007-7-7 14:56:10 > top of Java-index,Archived Forums,Socket Programming...
# 2

I came across this issue. My JSP page is a very lengthy one and it has lot of combo boxes. Whenever user selects some data, the page refreshes and scroll moved to top of the page. What I did was, based on the mouse click I have calculated the vertical scroll amount in pixels and moved my scroll automatically. Just 4 lines of javascript code does it. Since page refreshes, I needed to store scroll amount in a form bean variable.

skp71 at 2007-7-7 14:56:10 > top of Java-index,Archived Forums,Socket Programming...
# 3

@ktsystemteq

Hi friend,

Well i have coded a sample of the similar sort( which refersh table data in a div field but regarding implementation of scrollbar is upto you) where i have made use to XmlHttpRequest Object Calls (AJAX calls) to refersh the field view for every 10 secs. You might have a look of it and may check whether that suits your application or not....

Index.Jsp :

=======

<%@page language="java" %>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Automatic Drop-Down Updation</title>

<script language="javascript">

// Global Variable for XmlHttp Request Object

var xmlhttp

// Timer Variables

var c = 0

var t

/* Synchronized Counter Function */

function syncCount(){

document.getElementById('txt').innerHTML = "Timer : " + c

c = c+1

// Setting timeout for every second

t = setTimeout("syncCount()",1000)

// If Refershes the Table for every 10 seconds

if(c % 10 == 0 && c != 0){

// calling a Servlet to Refersh Drop-Down field

refreshCombo()

}

}

/* A function which calls a servlet named AjaxServlet to get XmlData using XmlHttpObject */

function refreshCombo(){

xmlhttp = null

// code for initializing XmlHttpRequest Object On Browsers like Mozilla, etc.

if (window.XMLHttpRequest){

xmlhttp = new XMLHttpRequest()

}

// code for initializing XmlHttpRequest Object On Browsers like IE

else if (window.ActiveXObject) {

xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")

}

if (xmlhttp != null){

// Setting the Servlet url to get XmlData

url = "AjaxServlet";

// Course of Action That Should be Made if their is a change in XmlHttpRequest Object ReadyState NOTE : it is 4 when it has got request from CGI

xmlhttp.onreadystatechange = getResponseAction;

// Open the Request by passing Type of Request & CGI URL

xmlhttp.open("GET",url,true);

// Sending URL Encoded Data

xmlhttp.send(null);

}

else{

// Only Browsers like IE 5.0,Mozilla & all other browser which support XML data Supports XmlHttpRequest Object // In the Below case it looks as if the browser is not compatiable

alert("Your browser does not support XMLHTTP.")

}

}

/* Used for verifing right ReadyState & Status of XmlHttpRequest Object returns true if it is verified */

function verifyReadyState(obj){

// As Said above if XmlHttp.ReadyState == 4 then the Page Has got Response from WebServer

if(obj.readyState == 4){

// Similarly if XmlHttp.status == 200 it means that we have got a Valid response from the WebServer

if(obj.status == 200){

return true

}

else{

alert("Problem retrieving XML data")

}

}

}

/* Action that has to take place after getting reponse */

function getResponseAction(){

// Verifying State & Status

if(verifyReadyState(xmlhttp) == true){

// Building a DOM parser from Response Object

var response = xmlhttp.responseXML.documentElement

// Deleting all the Present Elements in the Clearing Existing Table

drRemove()

// Checking for the Root Node

var x = response.getElementsByTagName("option")

var val

var tex

var optn

var txt = "<table border=1><tr><th align=center>Emp id</th><th align=center>Name</th></tr>"

for(var i = 0;i < x.length; i++){

optn = document.createElement("OPTION")

var er

txt = txt + "<tr>"

// Checking for the tag which holds the value of the Drop-Down combo element

val = x[i].getElementsByTagName("val")

{

try{

// Creating a table data field with "empid" of the employee

txt = txt +"<td>"+val[0].firstChild.data+"</td>"

} catch(er){

}

}

// Checking for the tag which holds the Text of the Drop-Down combo element

tex = x[i].getElementsByTagName("text")

{

try{

// Creating a table data field with "name" of the employee

txt = txt +"<td>"+tex[0].firstChild.data+"</td>"

} catch(er){

}

}

txt = txt + "</tr>"

}

txt = txt + "</table>"

document.getElementById('TableRefersh').innerHTML = txt

}

}

/* Function clears the present div value or clears the existing table*/

function drRemove(){

document.getElementById('TableRefersh').innerHTML = " "

}

</script>

</head>

<body onload="syncCount()">

<pre> <font color='blue' size='4'><div id='txt'></div></font></pre>

<div id='TableRefersh'></div>

</body>

</html>

AjaxServlet.java :

============

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

/**

*

* @author RaHuL

*/

public class AjaxServlet extends HttpServlet {

/** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.

* @param request servlet request

* @param response servlet response

*/

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Sets the content type made to xml specific

response.setContentType("text/xml");

//Initializing PrintWriter

PrintWriter out = response.getWriter();

// Creating an instance of XmlBean Which generates XmlData From Business Logic specified

XmlBean xml = new XmlBean();

// Method to Generate XMLDATA

String buffer = xml.getXmlData();

// If Close of DB connections are succefull then write the content to the printstream

if(xml.close() == true)

out.write(buffer);

out.close();

}

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Calls a Method called processRequest Which Processes the request which was made by the Browser Page

processRequest(request, response);

}

}

XmlBean.java :

============

import java.sql.*;

import java.util.*;

import java.io.*;

/**

*

* @author RaHuL

*/

public class XmlBean {

private Connection con = null;

private PreparedStatement pstmt = null;

private ResultSet rs = null;

// Specifing CLASSNAME of the Driver Type

private String CLASSURL = "sun.jdbc.odbc.JdbcOdbcDriver";

/* Specifing CONNECTIONURL to a DSN named TestDsn

* Please Make Sure you create a DSN Named TestDsn to your database which holds EMP table

*/

private String CONNECTIONURL = "jdbc:odbc:TestDsn";

boolean IS_ESTABLISHED = false;

/** Creates a new instance of XmlBean and also establishes DB Connections */

public XmlBean() {

try{

Class.forName(CLASSURL);

con = DriverManager.getConnection(CONNECTIONURL,"admin","");

IS_ESTABLISHED = true;

} catch(SQLException sqe){

sqe.printStackTrace();

} catch(Exception exp){

exp.printStackTrace();

}

}

/* Generates XmlData For the Business Logic Specified */

public String getXmlData(){

String XmlBuffer = "";

if(IS_ESTABLISHED == true){

try{

pstmt = con.prepareStatement("SELECT empid,name FROM EMP");

rs = pstmt.executeQuery();

if(rs != null){

XmlBuffer = XmlBuffer + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>";

XmlBuffer = XmlBuffer + "<!-- Edited by Rahul Sharma-->";

// Root Node

XmlBuffer = XmlBuffer + "<SampleTable>";

while(rs.next()){

String value = rs.getString(1);

String text = rs.getString(2);

// Sub-root Node

XmlBuffer = XmlBuffer + "<option>";

// node which holds value of drop-down combo

XmlBuffer = XmlBuffer + "<val>"+value+"</val>";

// node which holds text for drop-down combo

XmlBuffer = XmlBuffer + "<text>"+text+"</text>";

XmlBuffer = XmlBuffer + "</option>";

}

XmlBuffer = XmlBuffer + "</SampleTable>";

}

}catch(SQLException sqe){

sqe.printStackTrace();

} catch(Exception exp){

exp.printStackTrace();

}

}

return(XmlBuffer);

}

/* Closes the DB Connection Conmpletely */

public boolean close(){

if(IS_ESTABLISHED == true){

try{

pstmt.close();

con.close();

return(true);

} catch(SQLException sqe){

sqe.printStackTrace();

} catch(Exception exp){

exp.printStackTrace();

}

}

return(false);

}

}

Sample XML String generated from the XmlBean :

=======================================

<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>

<!-- Edited by Rahul Sharma-->

<SampleTable>

<option>

<val>3244</val>

<text>Ram</val>

</option>

<option>

<val>3245</val>

<text>Robert</val>

</option>

<option>

<val>3246</val>

<text>Rahim</val>

</option>

</SampleTable>

REGARDS,

RAHUL

RahulSharna at 2007-7-7 14:56:10 > top of Java-index,Archived Forums,Socket Programming...
# 4

> I came across this issue. My JSP page is a very

> lengthy one and it has lot of combo boxes. Whenever

> user selects some data, the page refreshes and scroll

> moved to top of the page. What I did was, based on

> the mouse click I have calculated the vertical scroll

> amount in pixels and moved my scroll automatically.

> Just 4 lines of javascript code does it. Since page

> refreshes, I needed to store scroll amount in a form

> bean variable.

Would it be possible to view some sample code of this

ktsystemteq at 2007-7-7 14:56:10 > top of Java-index,Archived Forums,Socket Programming...
# 5
Hi Rahul,I am going to try and look at the example you gave me.The main thing I need is to retain the position of the scrollbar of the table in the div after every refresh.
ktsystemteq at 2007-7-7 14:56:10 > top of Java-index,Archived Forums,Socket Programming...
# 6

function scrollingPos(){

//store the scrolling position in the hidden (whichpos)

var mypos = 0;

mypos = document.body.scrollTop;

document.forms[0].whichpos.value = mypos;

}

function gohere() {

//while loading form, get the 'whichpos' value from the server and pass to scrollTo

var thispos = '<%= scrollpos %>';

window.scrollTo(0,thispos);

}

<%

String scrollpos = (String)request.getAttribute("scrolval");

%>

<html:hidden name="rForm" property="whichpos"/>

<html:select property="ra" onchange="scrollingPos();" multiple="true" >

<html:optionsCollection property="rList" value="name" label="name"/>

</html:select>

Generate a getter/setter for whichpos in the form bean.

private int whichpos = 0;

skp71 at 2007-7-7 14:56:10 > top of Java-index,Archived Forums,Socket Programming...
# 7

I dont know if what i am doing is right.

please tell me if what i have done is right or wrong

I created a nForm.java file with the following code and i have put it with the rest of the Bean files:

import java.util.*;

public class nForm

{

private int whichpos = 0;

public void setWhichPos(int num)

{

whichpos = num;

}

public int getWhichPos()

{

return whichpos;

}

}

then i put this in the HEAD section of my jsp pages:

<script>

function scrollingPos(){

//store the scrolling position in the hidden (whichpos)

var mypos = 0;

mypos = document.body.scrollTop;

document.forms[0].whichpos.value = mypos;

}

function gohere() {

//while loading form, get the 'whichpos' value from the server and pass to scrollTo

var thispos = '<%= scrollpos %>';

window.scrollTo(0,thispos);

}

</script>

then this in the body of the jsp pages:

<%

String scrollpos = (String)request.getAttribute("scrolval");

%>

<html:hidden name="nForm" property="whichpos"/>

<html:select property="ra" onchange="scrollingPos();" multiple="true" >

<html:optionsCollection property="rList" value="name" label="name"/>

</html:select>

and then also:

<BODY onload="gohere()">

i get an error when i load the page though

org.apache.jasper.JasperException: Unable to compile class for JSP

An error occurred at line: 29 in the jsp file: /pages/testpages/ihms/tester.jsp

Generated servlet error:

scrollpos cannot be resolved

ktsystemteq at 2007-7-7 14:56:10 > top of Java-index,Archived Forums,Socket Programming...
# 8

@ktsystemteq

try

<%

String scrollpos = (String)request.getAttribute("scrolval");

%>

<script>

function scrollingPos(){

//store the scrolling position in the hidden (whichpos)

var mypos = 0;

mypos = document.body.scrollTop;

document.forms[0].whichpos.value = mypos;

}

function gohere() {

//while loading form, get the 'whichpos' value from the server and pass to scrollTo

var thispos = <%= scrollpos %>;

window.scrollTo(0,thispos);

}

</script>

<BODY onload="gohere()">

-

-

Try something of this kind for you compilation problem....

btb wat happened wid my implementation.... ?

RahulSharna at 2007-7-7 14:56:10 > top of Java-index,Archived Forums,Socket Programming...
# 9
Hi Rahul,I couldn't get your implementation to work.I kept getting the "Problem retrieving XML data" message. I think your implementation is what I will be working to achieve but I don't quite understand it all yet but I am using your code to learn.
ktsystemteq at 2007-7-7 14:56:10 > top of Java-index,Archived Forums,Socket Programming...
# 10

The pages appears now after i put the declaration about the script.

when i change this line to:

var thispos = '500';

the scrollbar changes to position 500 after every refresh

but it does not retain any position in its original code:

var thispos = '<%=scrollpos %>';

do you think i should call another method or function to get the previous scrollbars position? but it seems like the scrollpos should already do that

ktsystemteq at 2007-7-7 14:56:10 > top of Java-index,Archived Forums,Socket Programming...
# 11

Hope you have added this scriptlet at the top of the JSP.

<%

String scrollpos = (String)request.getAttribute("scrolval");

%>

In my JSP, it holds the value based on the latest mouse click. My JSP is very lengthy one and it has lot of pair of list boxes. In every pair, 2nd list box values are based on 1st list box value. After I click, 1st list box page referesh to get 2nd list data. So scollpos holds the value of 1st list box position in pixel (whereever it is).

skp71 at 2007-7-7 14:56:10 > top of Java-index,Archived Forums,Socket Programming...
# 12
In my situation there is no list selection. It is just a page that refreshes automatically every 10 seconds. How would you suggest I get and hold the pixel position?
ktsystemteq at 2007-7-7 14:56:10 > top of Java-index,Archived Forums,Socket Programming...
# 13
In your case just put a hardcoded value whatever you want. I think, this is not the right solution for your case. Also, except this there is no other solution too.
skp71 at 2007-7-7 14:56:10 > top of Java-index,Archived Forums,Socket Programming...
# 14

@ktsystemteq

Well Friend as far as i see there could be 2 solutions for your problem.

1). By getting the current position of the scrollbar and sending it to Servlet / JSP Saving the value in session and getting reponse back to JSP with set of initializations and reload of the whole page.

2).All you have to do is instead of going with a page refersh just refersh the view which you wanted using AJAX or by any other workaround technique.

Its is upon you of how to go about this.

RahulSharna at 2007-7-7 14:56:10 > top of Java-index,Archived Forums,Socket Programming...
# 15
I think i will want to get the position of the scroll bar and send it to the servlet and then get the response back.This way is similar to skp71's suggestion is it now? I am just a little bit confused on how servlets work but im slowly learning it.
ktsystemteq at 2007-7-7 14:56:12 > top of Java-index,Archived Forums,Socket Programming...
# 16
n
ktsystemteq at 2007-7-7 14:56:12 > top of Java-index,Archived Forums,Socket Programming...
# 17

Yes exactly, I was refering to the method suggested by the other poster itself

In that case you have to call a Controller which brings you that data and forwards it back to you. but by doing this your page gets refershed.

In order to get the present state of the form you have to save the entire state in scope of request / bean depending on fwd or redirect of the request. In your case it is the position of the scrollbar. so you have to write a function which encodes Scrollbar position in the URL along with the existing request pattern so that the servlet can store the attribute inside the scope of request and forward it back to you or store it in session and redirect it back to you.

RahulSharna at 2007-7-7 14:56:12 > top of Java-index,Archived Forums,Socket Programming...
# 18
how did you get the "scrollval"?what is the method/function you used to determine "scrollval" as a String?
ktsystemteq at 2007-7-7 14:56:12 > top of Java-index,Archived Forums,Socket Programming...
# 19

Just as an example why dont U try the javascript function to find cursor

function getPosition(e) {

e = e || window.event;

var cursor = {x:0, y:0};

if (e.pageX || e.pageY) {

cursor.x = e.pageX;

cursor.y = e.pageY;

}

else {

var de = document.documentElement;

var b = document.body;

cursor.x = e.clientX +

(de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);

cursor.y = e.clientY +

(de.scrollTop || b.scrollTop) - (de.clientTop || 0);

}

return cursor;

}

Hope this helps

RahulSharna at 2007-7-7 14:56:12 > top of Java-index,Archived Forums,Socket Programming...
# 20

I can now retrieve the position of the scrollbar but I do not know how to store the value. E.g using a bean or request.setAttribute.

Im not too sure how to use it even though i have tried some coding...is there anymore sample code for storing the int value of the scrollbar position and then reusing it when on page onload

ktsystemteq at 2007-7-7 14:56:12 > top of Java-index,Archived Forums,Socket Programming...