I have an issue, my whole JSF application is based on Ajax Requests
We do every request and everything using Ajax
The problem is when the session is timed out and the user tries to do anything on the page it just do nothing.
I know that the session is timed out but I wasn't able to catch it. after some trying finally I'm able to catch when the session is timed out after each request. but the problem now is to redirect the user to the login screen again from the filter or the managed bean or even using js
Please anyone can tell me what to do to redirect the user to the login screen
also please keep in mind that I have three pages in my application : login and index and logout only and everything is in the index page
Thanks in advance
you can use something like that in order to make an ajax redirection inside your timeout filter. You can refer to this thread
String facesRequestHeader = httpServletRequest
.getHeader( "Faces-Request" );
boolean isAjaxRequest = facesRequestHeader != null
&& facesRequestHeader.equals( "partial/ajax" );
if( isAjaxRequest )
{
String url = MessageFormat.format( "{0}://{1}:{2,number,####0}{3}",
request.getScheme(), request.getServerName(),
request.getServerPort(), timeoutPath );
PrintWriter pw = response.getWriter();
pw.println( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" );
pw.println( "<partial-response><redirect url=\"" + url
+ "\"></redirect></partial-response>" );
pw.flush(););
}
else
{
httpServletResponse.sendRedirect( timeoutPath );
}
Related
I'm trying to do a simple login to a website and at the end I print out the title to check if it's logged in, however for some reason I keep getting the title of the login screen.
Response res = Jsoup
.connect("http://moj.tvz.hr")
.data("login", "gost", "passwd", "gost")
.method(Method.POST)
.execute();
Map<String, String> cookies = res.cookies();
Document subjectPage = Jsoup.connect("https://moj.tvz.hr")
.cookies(cookies)
.get();
String subjectTitle = subjectPage.title();
System.out.println("##### Printing webpage title #####\n" + subjectTitle + "\n");
Testing login on the actual website works just fine with the user/pw combination, so I assume something is wrong with the rest of the code, but I can't seem to find what.
If you examine what data are send with a form request, for example with browser debugging tool you will find out, that for this site there is additional parameter TVZ. It is generated for your initial request. You have to parse it out and then add to login form request.
When you are connecting to other pages you have to add TVZ as a parameter to your request. Also you have to use cookies from initial request, because login response does not return any.
See code below.
Response initResponse = Jsoup.connect("http://moj.tvz.hr").execute();
Document doc = initResponse.parse();
String tvz = doc.select("input[name=TVZ]").attr("value");
Map<String, String> cookies = initResponse.cookies();
Response res = Jsoup.connect("https://moj.tvz.hr").data("login", "gost", "passwd", "gost")//
.data("TVZ", tvz)//
.cookies(cookies)//
.method(Method.POST).execute();
System.out.println("##### Printing webpage title #####\n" + res.parse().title() + "\n");
Document subjectPage = Jsoup.connect("https://moj.tvz.hr").data("TVZ", tvz).cookies(cookies).get();
String subjectTitle = subjectPage.title();
System.out.println("##### Printing webpage title #####\n" + subjectTitle + "\n");
I'm struggling with a rather troublesome problem. I'm making a web application using the following jsp/servlets.
GameServlet
Scene.jsp
PageServlet
GameServlet creates a new HttpSession and then sets a number of attributes I expect to use later.
GameServlet then forwards to Scene.jsp using the following code:
HttpSession session = request.getSession();
session.setAttribute("cur_game", game);
session.setAttribute("logic", logic);
session.setAttribute("cur_scene", scene);
session.setAttribute("session_id", session.getId());
out.println("Loaded session attributes");
if (debug == null) {
String target = "/Scene.jsp";
RequestDispatcher rd = request.getRequestDispatcher(target);
rd.forward(request, response);
}
In Scene.jsp I display the session id for later comparison. This works and also displays the other attributes in the session.
Then a button calls a function using the following code:
<script>
function gotoPage(target)
{
Str = "PageServlet?page=" + target;
window.location = Str;
}
</script>
However PageServlet doesn't seem to recognise the previous session. I check with this with the following code:
HttpSession sesh = request.getSession(false);
if(sesh==null)
out.println("Session is Null!");
else
out.println("<br/>Session id: " + sesh.getId());
And currently it displays that "Session is Null"
If anybody could provide some help it would greatly appreciated!
Many Thanks
Alex
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);
});
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
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.