Short version-display home page only if session is already created
Details
I have a login.html. It links to validation.jsp. It checks for password and then redirects to the following page.
But I want that this following page to be displayed only when the
validation is true. Otherwise if someone enters the link to the page
and finds that the page has not been logged into, it will prompt to
do it so.
It worked fine in the servlet. I created a new session in validation page
and set request.getSession(false) in the home page.
but this doesnt seem to work in jsp. If I set session=false in the page
directive, then I can not access session object at all. and if I
explicitly do what I have done in the page, it still doesn't work!!
<%# page language="java" import="java.io.*"
contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"
import="java.util.*;"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
session=request.getSession(false);
if(session==null)
{
out.println("please login");
}
else
{
out.println("how did it run!!! ??");
out.println(application.getAttribute("one"));
out.println(session.isNew());
out.println(session.getId());
out.println("<form action='logout.jsp' method='post'>");
out.println("<input type='submit'>");
out.println("</form>");
}
%>
</body>
</html>
You don't use if(session==null) to determine if someone is logged in. Sessions are generally created automatically, and besides, you might want to use a session for something even before login. You check for a specific session attribute.
String userid = (String)session.getAttribute("userid");
if(userid!=null)
{
out.print("logged in as:" + userid);
}
Of course in the login code you have to set it:
session.setAttribute("userid", userid);
There is also no need to call request.getSession in JSP. In a servlet you would need to, but in JSP the session object is already populated with request.getSession for you.
Edit:
When you do the session=false directive then the session object isn't declared so you'll need not just to set it but actually declare it: HttpSession session = request.getSession(false); Then you will get session=null, but its dangerous to rely on this for security, as going to a page where you didn't set session=false will create the session, and your code will then think someone was validly logged in, when they were not. Even if you are certain that you put session=false everywhere, you might miss a spot, or more likely, the next developer after you will not understand you did it this way, and a security disaster is just waiting to happen.
Using session=false is intended for performance boost not security. E.g. you have a faq page that doesn't care about sessions, set session=false so people going to that link doesn't create sessions and waste memory.
A JSP creates a session by default. If you don't need session then use following
<%# page session="false" %>
Related
I have a problem that's when I connect with two differents users using servlet and JSP , infromations of the first user keeps shown when I connect with any other user even I invalidate session when the connected user logout and I'm using
<meta http-equiv="Cache-Control" content="no-cache" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />
in all JSP pages , any other ideas please ? Thanx
you can copy and paste this code in every page of your site which clears the cached page.
<%response.setHeader("Cache-Control","no-cache");
response.setHeader("Cache-Control","no-store");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);
if(session.getAttribute("some_token")==null)
response.sendRedirect("login/login.html");
%>
In logout you must be invalidating session so when you click back it would check the some_token attribute value in session and if not there it will redirect you to login page . But remember after login you are setting some_token attribute in session.
Hi i am trying to include a new jsp page on my jsp page in every 10 sec how can i achieve this
i am able to include page but not including according to time
Here is my code
<%# page language="java" contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html>
<head>
<title>Untitled Document</title>
section
{height:70%; background-color:blue; display:block; overflow:auto;}
section .push {height:500px;}
</style>
</head>
<body>
<form action="F1.jsp" method="post">
<%# include file="F2.jsp" %>
<footer>footer</footer>
</form>
</body>
</html>
How can i achieve this
Thanks in advance
If you want to include more content or refresh a section of the page you need to use browser side JavaScript to pull new content from the server.
Once you display something using JSP, that is final. It cannot change unless you provide the mechanisms to change. You can set a refresh rate of your JSP to auto refresh and display each time a new content.
Or you can use AJAX.
How to do it using ajax (I prefer the JQuery version) can be found here at the answer with 5 upvotes
You can set interval in Javascript.
syntax:
setInterval(function(){
// code //
},10000);
In the code you can use Ajax calls which pool the content of JSP from the server.
I am using gwt and the gwt is including in my jsp like below
Once i clicked the menu item it is taking me to myJsp.jsp which includes gwt module and i am displaying form with upload button.
Once i click the upload, it is uloading a file (and get the blobKey) and returns back to the same jsp(myJsp.jsp) but here before dispatching to this jsp(second time) i am setting one attribute in the request.
I am trying to get that attribute in the jsp by using ${ImportId} but i am getting empty value.
The below is my jsp.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<script type="text/javascript" language="javascript" src="/ActivityLog/ActivityLog.nocache.js">
</script>
</head>
<body>
<iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' class="iframe"></iframe>
<div class="wrapper">
<input type="hidden" name="memcacheHeaderId" value="${importId}" />
<div id="activityLogModule">
</div>
</div>
</div>
</body>
</html>
When ever executing gwt module ${importId} is null.
Second time before dispatching to this jsp, i am setting request.setAttribute("importId", importId); but in the jsp i am not getting this value
What might be the reason, Is there scope problem?
the only reason is you are setting value in request, as your request is completed, server discard your request.
when you are setting
request.setAttribute("importId", importId);
Than you must be redirecting to the JSP, which creates a new Request for the JSP to the Server. Meaning server creates a new request object and does not remembers the old object with your attribute set into it.
I am not much aware of gwt but in JSP-Servlet, there are 2 mechanisms 1)Redirect and 2)Forward. we use Forward mechanism to go to the JSP with the Same request object, so the attribute which is set into the Object is available on the JSP as well, because it is a copy of the request object passed in the Request.
So please check what you can do in GWT.
i have a requirement that only one user will be allowed to log in using one login id and password that means not two users will be allowed to login using the same username and id.so i thought to make a field in my Db to store the ipaddress.Suppose A has logged in then his ip address will be stored in Db and now if B wants to login then he will get alert that this user has already logged in and the ip address is A's ipaddress.and for that purpose i am using
<%# page import="java.net.*" %>
<%# 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>Insert title here</title>
</head>
<body>
<%
out.println("remote address "+request.getRemoteAddr());
out.println("remote host "+request.getRemoteHost());
out.println("remote port "+request.getRemotePort());
out.println("remote user "+request.getRemoteUser());
//out.println(InetAddress.getLocalHost().getHostAddress());
out.println(request.getRemoteAddr());
//out.println(InetAddress.getLocalHost().getHostAddress().toString());
%>
</body>
</html>
but i am not getting the exact ipaddress.please tell me how to get the ipaddress.if you think this way of storing ipadddress in Db and alerting to duplicate user is not wise then yours suggestions are also welcome
remote address 0:0:0:0:0:0:0:1 remote host 0:0:0:0:0:0:0:1 remote port 38059 remote user null 0:0:0:0:0:0:0:1
For some reason, request.getRemoteAddr() did not work for you. It is quite impossible to say why without knowing the company's network you are working in.
However, you do not even need the IP-address for that. Just keep a flag if the user is currently logged in:
User | logged in?
-----+------------
A | Yes
B | No
C | No
Now, if a user tries to login, check if he/she is already logged in. If so, display an error message and avoid login.
You need to reset this flag
When the user logs out (clicking the "logout" button)
After the session times out (you can use a HttpSessionListener for that), in case that the user did not click "logout". Note: If you have a high session timeout (like 30 minutes), and the user forgets to click "logout", he/she will not be able to login for the rest of the session.
After the application is redeployed, if all sessions are destroyed then.
Good day!
I encountered the following error upon running my JSP program.
java.lang.IllegalStateException: PWC3991: getOutputStream() has already been called for this response
It seems like the html file inside my JSP doesn't work.
My code is as follows:
<%#page import = "java.util.*"%>
<%#page import = "javax.servlet.*"%>
<%#page import = "javax.servlet.http.*"%>
<%#page import= "session.*" %>
<%#page contentType="text/html" 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>JSP Page</title>
</head>
<body>
<%
Item item = (Item) request.getAttribute("invenItem");
if (item != null) {
out.println("<html><title>Inventory Item</title>");
out.println("<body><h1>Inventory Item Details:</h1>");
out.println("Stock ID : " + item.getStockID() + "<br/>");
out.println("Name : " + item.getItemName() + "<br/>");
out.println("Unit Price: " + item.getUnitPrice() + "<br/>");
out.println("On Stock : " + item.getOnStock() + "<br/>");
out.println("</body>");
out.println("</html>");
} else {
RequestDispatcher rd = request.getRequestDispatcher("DataForm.html"); //NOT WORKING
rd.include(request, response);
out.println("<br>Item not found...<br>");
rd = request.getRequestDispatcher("ItemEntry.html"); //NOT WORKING
rd.include(request, response);
}
%>
</body>
</html>
My html Files are located inside the folder WEB-INF. How can I make it work? DO i need to import it also? Thank you.
Don't use scriptlets (those <% %> things). JSP is a template technology for HTML. You don't need all those nasty out.println() things for HTML. Just write HTML plain in JSP.
So, instead of
<%
out.println("<html><title>Inventory Item</title>");
%>
just do
<html><title>Inventory Item</title>
(note that this results in invalid HTML, there should be only one <html> tag in a HTML page and only one <title> in the <head>, but that's a different problem, the w3 HTML validator should give a lot of hints and answers, also get yourself through some HTML tutorials)
JSP offers EL (Expression Language, those ${ } things) to access backend data, i.e. the data which is present as attribute in page, request, session and application scopes. It can be accessed using the attribute name.
So, instead of
<%
Item item = (Item) request.getAttribute("invenItem");
%>
use
${invenItem}
and instead of
<%
out.println("Stock ID : " + item.getStockID() + "<br/>");
%>
use
Stock ID: ${invenItem.stockID}<br/>
JSP also offers taglibs like JSTL to control the page flow and output.
So, instead of
<%
if (item != null) {
} else {
}
%>
use
<c:choose>
<c:when test="${invenItem != null}">
</c:when>
<c:otherwise>
</c:otherwise>
</c:choose>
JSP also offers <jsp:include> tag to include page fragments.
So, instead of
<%
RequestDispatcher rd = request.getRequestDispatcher("DataForm.html"); //NOT WORKING
rd.include(request, response);
%>
use
<jsp:include page="/WEB-INF/DataForm.jsp" />
(and rename it to .jsp)
And the exception will disappear.
See also:
JSP tag info page
How to avoid Java code in JSP files?
Java web development, what skills do I need?
Unrelated to the concrete problem, almost all of the links in this answer was already (in)directly given to you in your previous questions. Take them serious. To become a great programmer (as you ever stated in a question/comment), take some time to get yourself through those links (and the links in the links).
Firstly, try to avoid putting code onto your JSP page - it violates the MVC/separation of concerns paradigm that is a central part of JSP.
Second, plain old JSP's getting a bit old - using JSF/facelets/etc is recommended these days.
As for your actual problem, I'm not totally familiar with the technique you're employing, but the exception basically means that you've tried to send content after the latest point at which your able to (generally, after sending headers). In this case, I think what's happening is that you've already started sending the current page when you ask it to send a different page.
Simplest fix I can think of: rather than trying a conditional include based on results, just redirect to a different page.
The error indicates that the error lines of code cannot be called once something has been printed out to the output stream in jsp (including even the doctype declaration)
So you can try to put those pieces of code at the top of your page.
You can not use
out.print() and Requestdispatcher simultaneously....
It means after execution of out.print() there should not be any execution of statement with requestdispatcher.forward()....
So remove out.println() form else block.