Why are cookies not being destroyed in Java MVC website - java

I am attempting to prevent users viewing a webpage if they are not logged in.
Currently the user is able to "login" which sets a cookie for 24 hours. I achieve this using AJAX which forwards to the admin page after creating the "loggedIn" cookie.
When a user navigates to MainController?page=logout it should delete the cookie and forward the user to the login page, which it appears to do.
But when navigating to MainController?page=admin the user should be forwarded to the login page if no cookies exist, but instead the admin page loads. I'm assuming that I'm not deleting the cookies properly?
Here is the AJAX call to check user credentials when logging in:
$("#loginForm").submit(function(e){
e.preventDefault(); //STOP default action
var postData = $("#loginForm").serializeArray();
var username = $("#username").val();
var password = $("#password").val();
var botCatcher = $(".botCatcher").val();
if(username.length > 3 && password.length > 3 && botCatcher.length == 0){
$.ajax(
{
type: "POST",
url : "MainController",
data : postData,
success: function(data)
{
if(data == "success"){
window.location.href = "MainController?page=admin";
}else if(data == "nope"){
$(".test").html("<p>Login details incorrect. Please try again.</p>");
}
},
error: function(jqXHR, textStatus, errorThrown)
{
$(".test").html("<p>ss"+errorThrown+textStatus+jqXHR+"</p>");
}
});
}else{
$(".test").html("<p>Unable to login: ensure details are correct.</p>");
}
});
This is how I'm setting the cookie in the doPost method of the MainController servlet and outputing "success" to allow JQuery to forward to the admin webpage.
Cookie loggedIn = new Cookie("loggedIn", "true");
loggedIn.setMaxAge(60 * 60 * 24);
response.addCookie(loggedIn);
out.print("success");
This is how I control the navigation, as you can see the logout case should delete the cookie which means that the admin case should forward the user to the login page because the cookie object is null? Instead it loads the admin page. - This is actuated using a link on the admin page pointing to MainController?page=logout which is supposed to delete the cookie and forward to the login page, which it appears to do. But I can still navigate back to the admin page without needing to login.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String page = getPageName(request.getParameter("page"));
Cookie cookies[] = request.getCookies();
switch (page) {
case "admin":
if (cookies == null) {
page = "login";
return;
}
break;
case "logout":
for (Cookie cookie : cookies) {
cookie.setMaxAge(0);
cookie.setPath("/");
response.addCookie(cookie);
}
page = "login";
break;
}
RequestDispatcher rd = getServletContext().getRequestDispatcher(views + getPageFilename(page));
rd.forward(request, response);
}
Why is it loading the admin page instead of forwarding to the login page ( and thus preventing users not logged in to view this page ). Am I not deleting the cookies correctly?

Related

HtmlUnit stays logged in after removing "JSESSIONID" cookie

I'm setting up remember-me authentication for my Spring Boot application an want to write a HtmlUnit test.
The problem is that deleting the "JSESSIONID" cookie does not seem to log out the webClient.
The test using remember-me authentication works fine but the test in which there should be no authentication and thus a redirect to the login page does not work (the last assertion fails).
#Test
void NoRememberMeLogin() throws IOException {
HtmlPage loginPage = webClient.getPage(baseURL + "login");
HtmlForm loginForm = loginPage.getFormByName("loginForm");
HtmlInput username = loginForm.getInputByName("username");
HtmlInput password = loginForm.getInputByName("password");
HtmlCheckBoxInput rememberMe = loginForm.getInputByName("remember-me");
username.setValueAttribute("user");
password.setValueAttribute("password");
rememberMe.setChecked(false);
// login
HtmlElement submit = loginForm.getOneHtmlElementByAttribute("input", "type", "submit");
HtmlPage afterLogin = submit.click();
// login successful?
assertThat(afterLogin.getUrl().toString(), is(baseURL + "securedPage"));
// checkl cookies
Cookie sessionCookie = webClient.getCookieManager().getCookie("JSESSIONID");
Cookie rememberMeCookie = webClient.getCookieManager().getCookie("remember-me");
assertNotNull(sessionCookie);
assertNull(rememberMeCookie);
// delete the Session cookie
webClient.getCookieManager().removeCookie(sessionCookie);
sessionCookie = webClient.getCookieManager().getCookie("JSESSIONID");
// session cookie really is deleted
assertNull(sessionCookie);
// refresh tha page (works in browser)
afterLogin.refresh();
// check that we were redirected to login page (not working)
assertThat(afterLogin.getUrl().toString(), is(baseURL + "login"));
}
Hope you can help me, thanks!

how to send parameter from servlet to jsp page

I want to pass parameter from servlet to jsp page . That is why , in servlet , I have written the following code :
request.setAttribute("errorMessage", dbMessage);
response.sendRedirect(redirectURL + "index.jsp");
In index.jsp I have written the following code :
<%
String error_msg = (String)request.getAttribute("errorMessage");
out.println(error_msg);
if (error_msg != null) {%>
<div class="alert alert-danger">
<%=error_msg%>
</div>
<% } %>
But I do not have the value of errorMessage in index.jsp page. What is the reason ? Please help me . Point to be noted : error Message is not null .
You can not pass hidden params while using request.sendRedirect. You have following options to pass parameters to the JSP from servlet.
Set request params in the url itself as
response.sendRedirect(redirectURL + "index.jsp?errorMessage=", dbMessage);
and then in JSP change code to
String errorMsg = request.getParameter("errorMessage")
Error message will be visible in URL on the browser side.
Use server-side forwarding as mentioned in the answer by Jaydip as shown below.
request.setAttribute("errorMessage", dbMessage);
RequestDispatcher dispatcher = serveltContext().getRequestDispatcher("/index.jsp");
dispatcher.forward(request, response);
Using session
request.getSession().setAttribute("errorMessage", dbMessage);
on the JSP, change code to
String error_msg=(String)request.getSession().getAttribute("errorMessage");
Using cookie
Cookie errorCookie = new Cookie("errorMessage", dbMessage);
errorCookie.setPath(request.getContextPath());
response.addCookie(errorCookie);
On browser side you can read cookie via js or from the request itself
String error_msg = null;
Cookie [] cookies = request.getCookies();
for (Cookie cookie : cookies) {
if ("errorMessage".equals(cookie.getName())) {
error_msg = cookie.getValue();
}
}
You should write like this:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
**request.getSession().setAttribute("mango", "Mango is a sweet Fruit");**
response.sendRedirect(request.getContextPath() + "/index.jsp");
}
The problem here is you are using sendRedirect. Understand that sendRedirect will initiate new request to different url. Try to using forward or include to maintain the request parameter.

Checking for sessions in servlet or jsp

Suppose I have a servlet that processes logins. When the login is successful the user will create a session for this user. Then redirects to a homepage.
Let's say the homepage has a link "view all". This link calls a servlet, viewall.html to process all the data from the database then redirect to a jsp page (viewall.jsp) that will display the data from the servlet.
Somewhere from the servlet viewall.html to the jsp viewall.jsp, I would like to have code that looks like this:
if (session attribute user is null) {
// redirect to the login page
} else {
// if in the servlet, retrieve the data from the database
// if in the jsp, display the data
}
What is the better way to check if there is a session, on the servlet or the jsp? Note I know about filters, let's say the project can't use filters.
It is the same using a servlet of a filter. The general way is :
in the servlet that processes login you
create a new session
Session old = request.getSession(false); // first invalidate old if it exists
if (old != null) {
session.invalidate();
}
Session session = request.getSession(true); // next create one
put the user id as attribute of the session
session.setAttribute("USERID", userId);
then in the element (filter of servlet) where you want to know whether you have a registered user :
Session = request.getSession(false);
if ((session == null) or (session.getAttribute("USERID") == null)) {
response.sendRedirect(homeUrl);
return; // no need to process further (if in a filter no need to go down the chain)
}
in the servlet after controlling you have a logged on user, forward to the jsp
request.getRequestDispacher("/path/to/displayer.jsp").forward(request, response);
That's all ...
If you want to check this before creating, then do so:
HttpSession session = request.getSession(false);
if (session == null) {
// Not created .
session = request.getSession();
} else {
// Already created.
}
If you don't care about checking this after creating, then you can also do so:
HttpSession session = request.getSession();
if (session.isNew()) {
// newly created.
} else {
// Already created.
}
<% if(session.getAttribute("sessionname")==null)
{
response.sendRedirect("index.jsp");
else
{
String activeUser=session.getAttribute("sessionname").toString();
}
I hope it helps you

Jsp session & Rediretion

I am new in jsp. I am trying to do redirection to login page when expire the session.
My code:
String sessionUser = null;
sessionUser = session.getAttribute("UserName").toString();
if(sessionUser == "" || sessionUser == null)
{
System.out.println("In login");
response.sendRedirect("login.jsp");
}
else
{
System.out.println("out login");
}
in above code i get error in line of
sessionUser = session.getAttribute("UserName").toString();
Error
HTTP Status 500 - An exception occurred processing JSP page
How can i do this?
From the error message and your description it seems you have written this code in JSP :
sessionUser = session.getAttribute("UserName").toString();
The above line can throw error if session is null or session doesn't have a UserName attribute .It is bad practice to write scriptlets in JSP.
You need to use a Filter to do anything closer to what you intend to do :
// Do not create session if it doesn't exist
HttpSession session = request.getSession(false);
// check if session is null
if(session != null) {
chain.doFilter(request, response);
} else {
// redirect to login page
response.sendRedirect("/login.jsp");
}
You can implement HttpSessionListener to listen to the session invalidation event. But a Listener is not a good choice here , because it is not tied to a request.

JSP: Error in forwarding page

This question is related to the previous one, when I click over an anchor
send email
it calls servlet using json
$("#Email").click(function() {
var option={
"action":"sendEmail"
};
$.getJSON('StudentManagementServlet',option, function(hasEmail) {
if(hasEmail == false){
// //view form to let user enter his email
$("#CommViaEmail").fadeIn("normal");
}
});
});
in servlet I handle the request
if (action != null && action.equals("sendEmail")) {
//open connection to db
con.setAutoCommit(false);
String email = ParentManagement.getParentEmail(con, stdNo);
if (email != null) {
String commResult = createAccountAndSendEmail(con, parentNo, email);
request.setAttribute("result", commResult);
request.setAttribute("incp", "ResultPage");
RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
dispatcher.forward(request, response); //doesn't make forward!!!!!
System.out.println(">>send email DONE!!");
con.commit();
return;
} else {
boolean hasEmail = false;
String json = new Gson().toJson(hasEmail);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
}
The problem here is if user has an email, then I send an email but request dosn't forward to result page, even the print statement is printed " System.out.println(">>send email DONE!!");" ??
You need to let JS/jQuery do that job. Let the servlet write true as JSON result and in JS do
if (hasEmail) {
window.location = 'index.jsp';
} else {
$("#CommViaEmail").fadeIn("normal"); //view form to let user enter his email
}
Or when you want to control the URL yourself, add the new location to the JSON
Map<String, Object> data = new HashMap<String, Object>();
data.put("hasEmail", true);
data.put("location", "index.jsp");
// ...
with
..., function(data) {
if (data.hasEmail) {
window.location = data.location;
} else {
$("#CommViaEmail").fadeIn("normal"); //view form to let user enter his email
}
}
You are making an AJAX request from the client and are trying to 'forward' that request in the server side.
AJAX requests DONT refresh the page. The hasEmail variable in javascript function will be a string containing the HTML of the index.jsp.

Categories