I have a web application implemented in Spring MVC, JSP having default timeout is 30 minutes.
I need to show alert in UI saying "Your session is going to end in 5 minutes. Please click OK to continue" if the session is going to expire in another 5 minutes.
How to achieve this in better way?
I found few answers here
Just interested to know if there is any other better way to do this.
try this out,below code works me fine
var cookieName = 'sessionMsg';
var message = 'Your session is Expires 5 min, click OK to continue';
function getCookie(name)
{
var name = name + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
function setSessionPrompt() {
var timeout = getCookie(cookieName) - new Date().getTime();
setTimeout(function(){
if (new Date().getTime() < getCookie(cookieName)) {
setSessionPrompt();
} else {
if(confirm(message)) {
// do your action here
}
}
}, timeout);
}
setSessionPrompt();
Related
When customer makes a deposit, this inserts a request in the database. When this happens, I want send an alert or play an alarm on a separate jsp (admin page containing list of approvals). Any ideas?
In case anyone is interested, I solved this by creating a polling function that runs on the header that sits on all pages via tiles framework.
var alert = document.createElement('audio');
var count2 = $.cookie('list');
function poll(){
setTimeout(function(){
$.ajax({
url: url
,type: "GET"
,success: function(data){
var count1 = data.info;
if(count1>count2){
count2 = count1;
alert.play();
$.cookie("list",count2,{path:'/'});
$("#approvalCount").html($.cookie("list"));
}else if(count1<count2){
count2 = count1;
$.cookie("list",count2,{path:'/'});
}
}
,dataType: "json"
,complete: poll
,timeout: 2000
})
}, 30000);
};
Once its inserted write a script to display an alert:
out.println("<script><script>alert('Value Got inserted successfully')</script>");
OR you can do it like this aswell:
%><script>alert("Value Got inserted successfully")</script><%
Actually I've been reading about this for a while but I couldn't understand it very well.
Here is a snippet of the Servlet "ProcessNurseApp" :
if (dbm.CheckExRegNumber(Candidate.getRegNumber()) == true) {
// Show him an alert and stop him from applying.
out.println("<script>\n"
+ " alert('You already Applied');\n"
+ "</script>");
out.println("<script>\n"
+ " window.history.go(-1);\n"
+ "</script>");
}
So when the form named "ApplicationForm" in the "Nurses.jsp" get submitted it goes to that method in servlet after some Javascript validation.
My issue is that I want to call that method
if (dbm.CheckExRegNumber(Candidate.getRegNumber()) == true)
in the JSP page without getting to servlet so I can update values without refreshing the page. I've been reading that using ajax with jQuery would be the best way to do that, so can anyone help me of calling the above if statement from jQuery by AJAX.
Try an ajax call to the servlet(not possible without calling servlet) to check whether the function returns true or false then return a flag according to the value(true or false). On that basis you can show an alert or anything else.
For ajax call, you can use:
$.post( "ajax/Servlet_Url", function( data ) { if(data==true) alert("You already Applied"); else window.history.go(-1);});
Refer to following Link for more details about jQuery post request.
https://api.jquery.com/jquery.post/
jQuery(document).ready(function($) {
$("#searchUserId").attr("placeholder", "Max 15 Chars");
$("#searchUserName").attr("placeholder", "Max 100 Chars");
$.ajax({
url:"../../jsp/user/userMaster.do",
data: { drpType : 'userType',lookType : "1" },
success: function (responseJson) {
var myvalue = document.getElementById("userTypeKey");
for(var val in responseJson)
{
valueType = val;
textOptions = responseJson[val];
var option = document.createElement("option");
option.setAttribute("value",valueType);
option.text = textOptions;
myvalue.add(option);
if(valueType == myvalue.value)
{
option.selected = "selected";
}
}
}
});
});
This is related with handling the scenario when some crazy user is holding down the F5 key to send unlimited requests to our server.
Our application is very much database and cache intensive and when such consecutive requests come in; our web application is crashing after some time. I know we need to fix the application cache handling and need to add some check at the web server but I am asked to take care of this issue in our code.
I am handling this on both Javascript and server side, but looks like still it is failing, so would like to know if you have any better solution.
My code is as follows:
Javascript Code:
function checkPageRefresh(e) {
e = e || window.event;
ar isPageRefreshed = false;
// detect if user tries to refresh
if ((e.keyCode == 116) /* F5 */ ||
(e.ctrlKey && (e.keyCode == 116)) /* Ctrl-F5 */ ||
(e.ctrlKey && (e.keyCode == 82)) /* Ctrl-R */) {
isPageRefreshed = true;
}
// only trigger special handling for page refresh
if (isPageRefreshed){
var lastRefreshTimeMillis= readCookie("last_refresh");
var currentTimeMillis = new Date().getTime();
// set cookie with now as last refresh time
createCookie(lastRefreshCookieName, currentTimeMillis);
var lastRefreshParsed = parseFloat(lastRefreshTimeMillis, 10);
var timeDiff = currentTimeMillis - lastRefreshParsed;
var F5RefreshTimeLimitMillis = <%=request.getAttribute("F5RefreshTimeLimitMillis")%>;
// if detected last refresh was within 1 second, abort refresh
if (timeDiff < F5RefreshTimeLimitMillis) {
if (e.preventDefault) {
e.preventDefault();
return;
}
}
} // end if (isPageRefreshed)
}
Java Code:
Queue<VisitsInfoHolder> recentlyVisitedUrls = (LinkedList<VisitsInfoHolder>)session.getAttribute(SupportWebKeys.RECENTLY_VISITED_URLS);
String urlBeingCalled = PageUrlUtils.getFullURL(request);
int maxCountOfRecentURLs = 3;
if(null != recentlyVisitedUrls){
//verify if last visit count is matching with the count provided
if(recentlyVisitedUrls.size() >= maxCountOfRecentURLs ) {
int noOfMatchingVisits = 0;
Long firstAccessedTime = 0l;
int count = 0;
for(VisitsInfoHolder urlIno : recentlyVisitedUrls) {
//Store the time stamp of the first record
if(count == 0 && null != urlIno) {
firstAccessedTime = urlIno.getTimeOfTheVisit();
}
count++;
//count how many visits to the current page
if(null != urlIno && null != urlIno.getUrl() && urlIno.getUrl().equalsIgnoreCase(urlBeingCalled)) {
noOfMatchingVisits++;
}
}
if (noOfMatchingVisits >= maxCountOfRecentURLs && (new Date().getTime() - firstAccessedTime) <= 1000){
LOGGER.error(">>>>> Redirecting the client to the warning page.");
VisitsInfoHolder currentVisitInfo = new VisitsInfoHolder(urlBeingCalled,new Date().getTime());
recentlyVisitedUrls.remove();
recentlyVisitedUrls.add(currentVisitInfo);
response.sendRedirect((String)request.getAttribute("F5IssueRedirectPage"));
LOGGER.error(">>>>> Redirected successfully.");
return;
}
else{
VisitsInfoHolder currentVisitInfo = new VisitsInfoHolder(urlBeingCalled,new Date().getTime());
recentlyVisitedUrls.remove();
recentlyVisitedUrls.add(currentVisitInfo);
session.setAttribute(SupportWebKeys.RECENTLY_VISITED_URLS, recentlyVisitedUrls);
}
}
else if (recentlyVisitedUrls.size() < maxCountOfRecentURLs) {
VisitsInfoHolder currentVisitInfo = new VisitsInfoHolder(urlBeingCalled,new Date().getTime());
recentlyVisitedUrls.add(currentVisitInfo);
session.setAttribute(SupportWebKeys.RECENTLY_VISITED_URLS, recentlyVisitedUrls);
}
}
else{
recentlyVisitedUrls = new LinkedList<VisitsInfoHolder>();
VisitsInfoHolder currentVisitInfo = new VisitsInfoHolder(urlBeingCalled,new Date().getTime());
recentlyVisitedUrls.add(currentVisitInfo);
session.setAttribute(SupportWebKeys.RECENTLY_VISITED_URLS, recentlyVisitedUrls);
}
Now I keep holding the F5 button then my Javascript is not understanding that the same key is held for longer time and server side code prints the following 2 loggers
Redirecting the client to the warning page.
Redirected successfully.
But in reality it is not redirecting any single time. I tried adding Thread.sleep(1000) before and after redirect, but still no luck.
Please let me know if you see any issue with my code or let me know if there is any better solution.
When you reproduce this problem are you the only person on your server? Can you reproduce this problem on your local dev instance? If so you really need to fix your server code such that it doesn't crash. You are doing something on your server that is too intensive and needs to be optimized.
Simply intercepting the F5 key on someone's browser is treating the symptoms not the disease. If you are having problems handling a single user hitting F5 really quickly it simply means you'll never be able to scale up to many simultaneous users because that's the exact same request/response pattern as a single user round tripping you with F5.
It's time to break out the profiler and check the timings on how long it takes to process a single request through the system. Then look for hotspots and optimize it. Also watch your memory usage see if you are cleaning things up or if they are growing off into infinity.
I have a List which shows Users
<g:form action="listUsers">
<g:select id="userListe" name="selectedUser" size="10" onchange="this.form.submit()"
from="${users.idToShow}"
value="${selectedUser.idToShow}"/>//edit: idToShow, not itToShow
</g:form>
I implemented a search function with JQuery, this one works so far
$(function() {
//When user types, start searching
$('#userSearch').keyup(function() {
$.post(search_url, { query: this.value },
//data stores the found values from server (works)
function(data) {
//first, remove all the values from the userList
$('#userListe').find('option').remove();
//split userID and Value, not important
var userArray = data.split(";");
for (var i = 0; i < userArray.length; i++) {
//split userID and Value, not important
var name = userArray[i].split(':')[0]
var id = userArray[i].split(':')[1]
/*
* This Line solves the problem. Now the Server knows it´s a User
*/
$j('#userListe').append('<option value="'+name+'">'+name+'</option>'
});
});
})
The search shows the correct User, but if I click on one (to change values for example), the server doesnt know it's a User, and just shows a null pointer exception.
I know this is kinda interdisciplinary stuff and maybe a bit to large for a support question, but Ill be happy about any small clue.
Thanks a lot, Daniel
method listUsers:
def listUsers = {
def foundUsers
def users
def selectedUser
foundUsers = User.list()
users = User.list(fetch: [User: foundUsers.IdToShow])
users.sort {it.IdToShow}
selectedUser = users.get(0)
if (params.selectedUser) {
selectedUser = User.findByIdToShow(params.selectedUser)
}
[users: users, selectedUser: selectedUser]
I’m building a J2EE web application which uses Oracle SSO with an OID back-end as the means for authenticating users.
If a user wants to use the application, first he must provide a valid login/password at SSO's login page.
When the user is done using the application, he may click on the logout button; behind the scenes, the action associated with this button invalidates the user’s session and clears up the cookies using the following Java code:
private void clearCookies(HttpServletResponse res, HttpServletRequest req) {
res.setContentType("text/html");
for (Cookie cookie : req.getCookies()) {
cookie.setMaxAge(0);
cookie.setPath("/");
cookie.setDomain(req.getHeader("host"));
res.addCookie(cookie);
}
}
Also, I have an onclick JavaScript event associated with the logout button, which is supposed to delete the SSO cookies by calling the delOblixCookie() function (as found in some Oracle forum):
function delCookie(name, path, domain) {
var today = new Date();
// minus 2 days
var deleteDate = new Date(today.getTime() - 48 * 60 * 60 * 1000);
var cookie = name + "="
+ ((path == null) ? "" : "; path=" + path)
+ ((domain == null) ? "" : "; domain=" + domain)
+ "; expires=" + deleteDate;
document.cookie = cookie;
}
function delOblixCookie() {
// set focus to ok button
var isNetscape = (document.layers);
if (isNetscape == false || navigator.appVersion.charAt(0) >= 5) {
for (var i=0; i<document.links.length; i++) {
if (document.links.href == "javascript:top.close()") {
document.links.focus();
break;
}
}
}
delCookie('ObTEMC', '/');
delCookie('ObSSOCookie', '/');
// in case cookieDomain is configured delete same cookie to all subdomains
var subdomain;
var domain = new String(document.domain);
var index = domain.indexOf(".");
while (index > 0) {
subdomain = domain.substring(index, domain.length);
if (subdomain.indexOf(".", 1) > 0) {
delCookie('ObTEMC', '/', subdomain);
delCookie('ObSSOCookie', '/', subdomain);
}
domain = subdomain;
index = domain.indexOf(".", 1);
}
}
However, my users are not getting logged out from SSO after they hit the logout button: although a new session is created if they try to access the index page, the SSO login page is not presented to them and they can go straight to the main page without having to authenticate. Only if they manually delete the cookies from the browser, the login page shows up again - not what I need: the users must provide their login/password every time they log out from the application, so I believe there must be something wrong in the code that deletes the cookies.
I’d greatly appreciate any help with this problem, thanks in advance.
Oracle have two web SSO products - Oracle Access Manager and Oracle Single Sign On. The Javascript code you have posted is for Access Manager, so it won't help you. Besides, you shouldn't need to do anything in Javascript to log the user out.
Have a look at the logout section of the OSSO docs. It recommends using the following code:
// Clear application session, if any
String l_return_url := return url to your application
response.setHeader( "Osso-Return-Url", l_return_url);
response.sendError( 470, "Oracle SSO" );
You need a page, with a name of logout, that includes those JavaScript functions.
That's what the documentation says:
The WebGate logs a user out when it receives a URL containing
"logout." (including the "."), with the exceptions of logout.gif and
logout.jpg, for example, logout.html or logout.pl. When the WebGate
receives a URL with this string, the value of the ObSSOCookie is set
to "logout.
Cookies don't "delete" untill the browser is closed.