session servlets and href tag - java

what I'm trying to do is relative simple
In my webapp there are these two servlets:
(I will write some pseudocode)
servlet A code: :
HttpSession sess = req.getSession();
String str = (String) sess.getAttribute("log");
if(str == null)
{
// send html page with a form
// to enter password and name
// data will be proceessed by servlet B
}
else
{
// send html page with a form
// to enter only a name
//data will be proceessed by servlet B
}
servlet B code: :
HttpSession sess = req.getSession();
String logged = (String) sess.getAttribute("log");
if(logged == null)
{
//check if password correct
if(correct)
{
sess.setAttribute("log","ok");
// print name
// and tell the user
// that next time password
// will not be requested
}
else
{
// print error message
}
}
else
{
// print name
}
for some reason the second time the servlet A is called after that the user filled in password and name correctly
str is null so the if part gets printed.
EDIT:
I discovered that if the user after inserting the password and
being redirected to servletB writes the url of servletA by himself
all goes right , but it odesn't work when the user gets back to the previous
page using a link created by servletA:
A HREF=\"http://localhost:8080/Blog/ServletA\" back
again , any suggestions why this happens?

I believe its not entering in your if(correct) block i.e. correct condition is not getting satisfied. Correct the condition there and make sure, it sets the log attribute in the session. Once a attribute is set into the session, its there until session expires or your remove it.

Related

Spring - HttpServletRequest object null when deleting JSESSIONID cookie?

I am testing a new functionality in my web app where i'm allowing the user to remain signed in even after the browing session expires. In order to achieve this, i have a "Keep me logged in" checkbox on my login page. Upon successful login, a cookie is created containing the userID and the login process continues normally. The first thing the first method in my main controller does is check for the presence of that cookie, read the userId in it, set the User object in the session correctly and bypass the login process, going directly to the home page. When the user signs out, the cookie is recreated with an expiration of 0 which means it's automatically deleted.
My Spring sessions last 30 minutes currently. I have successfully tested everything but i'm trying to replicate the Spring session expiring, which gets rid of the User object in memory and would normally force the user to login. In order to replicate it, i am deleting the JSESSIONID cookie from Chrome. When i do that, the HttpServletRequest object (which I am checking cookies on) is null.
Here is the first code that runs in my main controller :
#RequestMapping(value = {"/"}, method = RequestMethod.GET)
public String home(ModelMap model, HttpServletRequest request)
{
if (session.getAttribute("loggedInUser") != null)
{
return "home";
}
else
{
String userId = null;
for (Cookie cookie : request.getCookies())
{
if (cookie.getName().compareTo("MDHISStaySignedIn") == 0)
{
userId = cookie.getValue();
break;
}
}
if (userId != null)
{
session.setAttribute("loggedInUser", userService.findByUserId(userId));
return "redirect:/";
}
else
{
model.addAttribute("login", new Login());
model.addAttribute("register", new Register());
model.addAttribute("registering", false);
return "login";
}
}
}
Is it normal that my request object is null when deleting this cookie? Am i not correctly replicating the Spring session timing out by deleting it? This NullPointerException only happens when deleting this cookie and upon first running the web app, the controller does not thrown the exception when the cookie is created by the first run. Should i somehow be checking for this null value and redirecting the controller back to this method if it is?
Thanks!
The solution is to add the following method parameter :
#CookieValue(value = "MDHISStaySignedIn", defaultValue = "notFound") String cookie
This will assign the content of the cookie to the value if it's present and assign "notFound" if it is not. This way one can access cookies when the request object is null!

Copy and past URL in JSP is giving white page

I am new to this forum. I have a doubt about JSP/servlet in my application
I have developed an application in which user may search some data based on some criteria and he will get data from database(through Hibernate to servlet and to JSP). When some data is displayed on screen based on search he/she may try to copy the URL and forward to anyone or If he try to open in different browser it is showing an empty page.
eg: if i try to paste the link given bellow it is showing blank page
example link
but i need to display the data how this can be achieved.
Edited: After clicking on job search in menu bar as mentioned in comments the page will redirect to a servlet
if(action.equals("searchjob")){
String requireskills=request.getParameter("txt_requireSkills");
String location=request.getParameter("txt_locationName");
session.setAttribute("location",location);
String minexp1=request.getParameter("dd_minimum");
String maxexp1=request.getParameter("dd_maximum");
jobsearchDAO = new JobSearchDAOImpl();
List<JobPostInfo> data=jobsearchDAO.jobsearchlist(requireskills,location,minexp1,maxexp1);
if(data!=null && data.size()!=0){
//save data
if(!(session.getAttribute("LoginObject")==null)){
JobSeeker jobSeeker=(JobSeeker)session.getAttribute("LoginObject");
JobSearchCriteria jobsearchcriteria= new JobSearchCriteria();
jobsearchDAO=new JobSearchDAOImpl();
jobsearchcriteria.setKeyWords(requireskills);
jobsearchcriteria.setLocation(location);
JobSeeker jobseeker=(JobSeeker)session.getAttribute("jobseeker");
//
// jobsearchcriteria.setJobSeeker(jobseeker.getJobSeekerSn());
jobsearchcriteria.setJscTs(new Date());
int value=jobsearchDAO.savesearch(jobsearchcriteria);
System.out.println("savesearch value------>"+value);
}
session.setAttribute("jobsearchlist", data);
// session.setAttribute("success","Search Criteria is saved to database.");
response.sendRedirect("jobsearchresult.jsp");
}else
{
session.setAttribute("error","No Records found");
response.sendRedirect("jobsearch.jsp");
}
}
This is the code in DAOIMPL
public List<JobPostInfo> jobsearchlist(String requireskills,String location,String minexp1,String maxexp1) throws Exception{
long minexp;
long maxexp;
try{
session =getSession();
//Criteria Query
Criteria query=session.createCriteria(JobPostInfo.class,"jpost");
// if(minexp1.equals("0") && (maxexp1.equals("") || maxexp1==null)){
if((minexp1.equals("-1") || minexp1=="-1") && maxexp1==null){
}
else if(minexp1.equals("0")){
minexp=Long.parseLong(minexp1);
long min=1;
query.add(Restrictions.lt("jpost.experienceMin",min));
}else if(!(minexp1.equals("") || minexp1==null) && maxexp1.equals("-1")) {
minexp=Long.parseLong(minexp1);
query.add(Restrictions.ge("jpost.experienceMin",minexp));
}else if(!(minexp1==null && maxexp1==null)){
minexp=Long.parseLong(minexp1);
maxexp=Long.parseLong(maxexp1);
query.add(Restrictions.and(Restrictions.ge("jpost.experienceMin",minexp),Restrictions.le("jpost.experienceMax",maxexp)));
}
//For Location
if(!(location==null|| location.equals(""))){
query.createAlias("jpost.location","location");
query.add(Restrictions.like("location.locationName",location).ignoreCase());
}
//For Keyword
if(!(requireskills==null || requireskills.equals(""))){
query.add(Restrictions.like("jpost.requiredSkills","%"+requireskills+"%").ignoreCase());
}//requireskills
List<JobPostInfo> list = query.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
if(list.size()==0){
return null;
}else{
return list;
}
}catch(HibernateException e){
e.printStackTrace();
}finally {
close(session);
}
return null;
}
I solved my problem. It's a very basic mistake and I hope this will help others:
response.sendRedirect("jobsearchresult.jsp") is replaced by request.getRequestDispatcher("studentinformation.jsp").forward(request, response)
or include-method. The second thing is, the session is created and initialized with the servlet. When I copy the link in a different browser, a certain block of the servlet will be executed. Example:
action.equals("searchjob")
So at the time the session is not available yet, I initialize it in every block like separating declaration and initialization.

How can I alert message in Servlet code and sendredirect to JSP page?

I am trying to make a simple login page to deal with database using JSP, servlet with MVC concept and Data Access Object(DAO) and I am new in this. My problem now that I need to alert a box message in servlet if the user enters invalid name and password and sendRedirect to login.jsp page again. I set flag to be 1 if the user valid then do this if-check
if(validUserFlage == 1)
response.sendRedirect("User_Manipulation_Interface.jsp");
else {
//Here i want to alert message cause user invalid ??
response.sendRedirect("Admin_And_User_Login_Form.jsp");
}
searching for this i find this answer but i can`t understand how can i do it
the answer i found:
(( With send redirect you cant display the message where you want in the code. So as per me there might be two approaches. Display a message here and use include of requestdispatcher instead of send redirect or else pass some message to admin.jsp and display the message there. ))
Set a flag parameter like this,
response.sendRedirect("Admin_And_User_Login_Form.jsp?invalid=true");
on jsp
<c:if test=${invalid eq 'true'}">invalid credentials</c:if>
You can set the Parameters like errormsg in the servlet page and add it to the ri-direct object. Then you can check that variable errormsg and if it is null then the username is correct else the username is incorrect..
In Servlet Code:
if(username.equal(databaseusername))
{
RequestDispatcher rd = request.getRequestDispatcher("NextPage.jsp");
req.setAttribute("errormsg", "");
rd.forward(request, response);
}
else
{
RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
req.setAttribute("errormsg", "Wrong Username or Password");
rd.forward(request, response);
}
In JSP code:
<%
String msg=req.getAttribute("errormsg").toString();
if(!msg.equals(""))
{
// Print here the value of Msg.
}
%>
In servlet
String strExpired = (String) session.getAttribute("Login_Expired");
response.sendRedirect("jsp/page.jsp");
In jsp
<%
String strExpired = (String) session.getAttribute("Login_Expired");
out.print("alert('Password expired, please update your password..');");
%>

How do I show home page if user has a valid session?

How do I show a show home page if a user requests login page with a valid session using spring security?
if(session == null) {
// not valid
} else {
String username = (String) request.getParameter("username");
String age = (String) request.getParameter("age");
}
When you load the login page, check for a valid session. If a valid session exists, then you can redirect the page to your home page. Where as if there is no session, you can continue with display of login screen.

Can't log out from Oracle SSO

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.

Categories

Resources