What extra do I need to do while using HttpSession with GAE? - java

I read , to set a session attribute I need to put :
<sessions-enabled>true</sessions-enabled>
inside appengine-web.xml and also implement java.io.Serializable. (though I don't understand the reason for this !)
Following is one of the servlet that uses HttpSession :
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userName = request.getParameter("username");
String password = request.getParameter("password");
ArrayList list = new ArrayList();
if(userName.compareTo("user") != 0 ) {
list.add("Wrong Username");
} else if(password.compareTo("password") != 0) {
list.add("Wrong Password");
}
if(list.isEmpty()) {
HttpSession session = request.getSession();
if(session.isNew()) {
session.setAttribute("UserRole", "PW :Admin");
session.setMaxInactiveInterval(900);
RequestDispatcher rd = request.getRequestDispatcher("abc/cpanel/PcPanel.jsp");
request.setAttribute("SessionStatus", "JC"); // Just Created
rd.forward(request, response);
}
} else {
response.sendRedirect("abc/cpanel/PcPanel_Login.jsp");
}
}
After validating the username and password and entering the if block,request should be forwarded to PcPanel Login.jsp but it doesn't happen.Intead a blank page appears with the address of this servlet. But if I remove/comment all the session junk,it works fine. Why does it happen ? Am I missing something or I making a mistake somewhere ?

Don't use isNew(). isNew() is only true when session is first established = when user first lands on any of your pages.
See the answer to this question: Session is NOT working - GAE/J

Related

Finding why an Angular 5 service subscription is returning a null observable

I have the following service subscription in my component:
this.userService.loginUser(this.user).subscribe(users => {
if (users == null) {
console.log('users is null');
this.isValid = !this.isValid;
} else {
this.userService.subscribers.next(users);
localStorage.setItem('user', JSON.stringify(users));
console.log(`User, ${this.user.username}, successfully logged in!`);
console.log(localStorage.getItem('user'));
this.router.navigate(['dashboard']);
}
});
The service method looks like this:
public loginUser(user: User) {
console.log(`Attempting to login user: ${user.username}`);
const json = JSON.stringify(user);
this.currentUser = user;
return this.http.post<User>(API_URL + 'login', json, HTTP_OPTIONS);
}
The post request goes to this java servlet method:
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("login attempt");
if (req.getInputStream() != null) {
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(req.getInputStream(), User.class);
user = userService.loginUser(user);
if (user != null) {
user.setPassword("");
HttpSession session = req.getSession();
session.setAttribute("user", user);
}
}
}
On the java end, a username and password match is found and the session attribute is correctly set. However, on the Angular end, 'users' is null, as evidenced by the console.log('users is null') in the first code block. So my question is, why is this null? Can someone please help me understand the mechanics of this? I'm having a very hard time grasping how certain aspects of Angular even work...
So the problem was that in the servlet I didn't have a response. At the end I needed
PrintWriter out = resp.getWriter();
out.write(mapper.writeValueAsString(user));

Losing Attribute Hashmap in Session

I'm facing a trouble when try to get the hashmap from session. Below are my code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("userName");
String passWord = request.getParameter("passWord");
HttpSession session = request.getSession();
User user = new User(userName, passWord);
if(LoginUtils.DoInsert(user) == null) {
Map<String, User> listUser = (HashMap<String, User>) session.getAttribute("listUser");
User Sessionuser = (User)session.getAttribute("user");
response.sendRedirect("index.jsp");
}
else {
session.setAttribute("listUser", LoginUtils.getListUser());
session.setAttribute("user", user);
response.sendRedirect("index.jsp");
}
}
The first time, I persist Attribute listUser to session (else block) but the second time, when I tried to retrieve listUser, it get null here (if block). As the debugging, I can see, user Object is still inside the session but the listUser is not. This issue only happens when I use Eclipse, Netbeans works fine. I have tested on both IDE with the same code.
I'm not sure is something wrong with my code or Eclipse
Please give me some advices. Thanks so much

How to check in servlet that is an user new with session?

I am very new to java servlet programming. I have been writing a simple program for practicing java session. There are two .jsp file. first one called index.jsp, and another one is selection.jsp. And there is a servlet called controller. At first the index.jsp will be called, and user will be submit a input. That will be redirect in servlet controller. In that servlet will check whether it is new request or not. If new then it redirect to other page, else will do some other work.
I am checking whether it is new request or not by session.isNew() method. But it always says it is not new session. But, if I disable the browser cookies option then it is working fine. Now what is my observation is that when in the first I request the index.jsp to the container it assign a session along with that request. So when it comes to servlet it treat as a old session. I got this idea from Head first book Servlet and JSP.
Here is my servlet code -
public class Controller extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user;
HttpSession session = request.getSession(false);
if (session == null) {
user = request.getParameter("user");
if (user == null) {
response.sendRedirect("index.jsp");
}
session.setAttribute("username", user);
SelectItem selectItem = new SelectItem();
selectItem.setUser(user);
response.sendRedirect("selection.jsp");
session.setAttribute("selectItem", selectItem);
} else {
String selectionItem = request.getParameter("selection");
SelectItem selectItem = (SelectItem) session.getAttribute("selectItem");
if (selectItem != null) {
selectItem.add(selectionItem);
session.setAttribute("selectItem", selectItem);
}
response.sendRedirect("selection.jsp");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
So, how to determine whether it is a new session or old one? Thank you.
HttpSession.isNew API:
Returns true if the client does not yet know about the session or if the client chooses not to join the session. For example, if the server used only cookie-based sessions, and the client had disabled the use of cookies, then a session would be new on each request.
So, you're getting true because the client has cookies disabled. The "new session" check in done in the else block of this check:
HttpSession session = request.getSession(false);
if (session == null) {
// create new session
session = request.getSession();
} else {
// existing session so don't create
}
In your code, you don't appear to be creating a new session when a new session is detected. Perhaps that's where you're stumbling.
Note: learning the basic Servlet API is a good thing. However, for my professional work I use frameworks which simplify my programming, like Spring Boot and Spring Security.

Declare a session variable golbaly to access from DoGet and DoPost in a sevlet

I have a servlet where I need to declare a session which can be acceptable form doGet and doPost both how I should do this?
I have done
#WebServlet(name = "LoginLogout", urlPatterns = {"/LoginLogout.do"})public class LoginLogout extends HttpServlet {//For Session
HttpSession session = request.getSession(true);
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String status = request.getParameter("status");
System.out.println(status);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String loginId = request.getParameter("login_id");
String password = request.getParameter("password");
System.out.println(loginId);
//Inserting value to the Pogo named "newLoginPogo"
loginData newLoginPogo = new loginData();
newLoginPogo.setLoginId(loginId);
newLoginPogo.setPassword(password);
//Creating a obj of ModelLogin to send the loginId and Password via a method which is in ModelLogin class
ModelLogin loginBis = new ModelLogin();
loginData userData = loginBis.checkUser(newLoginPogo);
String userExist = userData.getUserExist();
System.out.println(userExist);
if ("yes".equals(userExist)) {
System.out.println("In while loop of Servlet");
String firstName = userData.getFirstName();
String userId = userData.getUserId();
boolean IsSu = userData.getIsSu();
//conveting boolean to string
String superuser = new Boolean(IsSu).toString();
//Creating a session
session.setAttribute("firstName", firstName);
session.setAttribute(userId, "userId");
session.setAttribute(superuser, "IsSu");
//==============================================================================================================
//If user does exist show the Success Message and forward Dashboard
//==============================================================================================================
//Session for success message
String succmsg = "Login Successful";
session.setAttribute("succmsg", succmsg);
getServletConfig().getServletContext().getRequestDispatcher("/WEB-INF/ViewPages/dashboard/dashboard.jsp").forward(request, response);
} //==============================================================================================================
//If user does not exist show the Error Message
//==============================================================================================================
else if ("no".equals(userExist)) {
//Session for success message
System.out.println("inside NO");
String emsg = "Login Error";
session.setAttribute("errmsg", emsg);
getServletConfig().getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
} else {
}
/*
//===============================================================================================================
//code for Logout
//===============================================================================================================
String status = request.getParameter("status");
if ("logout".equals(status)) {
//clearing the session
session.invalidate();
//forwarding to index page
getServletConfig().getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
}
*/
} finally {
}
}}
But it says
Can Not find Symbol
in this line HttpSession session = request.getSession(true);
You don't need to have session variable in servlet as field. In general - this is kind of common mistake. There will be only one onstance of servlet serving lots of requests, and unless you declare it as single-threaded - the requests would be handled concurrently.
HttpSession will be pre-exist for you in doGet and doPost via request object. Servlet container will guarantee this. So simply obtain reference to the session in doGet/doPost and do whatever you want.
What you desire is one of the roles of HTTP session.
You can look at it as a conversation between the client and the server.
As long as the "conversation" (HTTP session) is open and alive, you can set variables on the HTTP session, and access them from different requests that will sent on the same session.
Look at this as some sort of "shared memory" that exists during the "conversation time".
You can find many examples on how to do that over the internet.
Here is an example for session tracking.

HttpServletRequest#login() not working in Java

j_security_check just doesn't seem enough for me to perform login process. So, instead of submitting the form to j_security_check i created my own servlet and in that i am programmatically trying to do login. This works but i am not able to redirect to my restricted resource. Can anybody tell me what can be the problem? This is processRequest method of my servlet :-
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String strUsername = request.getParameter("txtusername");
String strPassword = request.getParameter("txtpassword");
if(strUsername == null || strPassword == null || strUsername.equals("") || strPassword.equals(""))
throw new Exception("Username and/or password missing.");
request.login(strUsername, strPassword);
System.out.println("Login succeeded!!");
if(request.isUserInRole(ROLES.ADMIN.getValue())){//enum
System.out.println("Found in Admin Role");
response.sendRedirect("/app/Admin/home.jsf");
}
else if (request.isUserInRole(ROLES.GENERAL.getValue()))
response.sendRedirect("/app/Common/index.jsf");
else //guard
throw new Exception("No role for user " + request.getRemoteUser());
}catch(Exception ex){
//patch work why there needs to be blogger here?
System.out.println("Invalid username and/or password!!");
response.sendRedirect("/app/Common/index.jsf");
}finally {
out.close();
}
}
Everything works fine and i can even see message "Found in Admin Role" but problem is even after authenticating i am not able to redirect my request to some other page.
i am not sure but i think this issue is the subject of
https://glassfish.dev.java.net/issues/show_bug.cgi?id=11340
Remove those lines, they doesn't belong there:
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
and
out.close();
If you close the OutputStream, the redirect cannot be taken place. You should in fact have seen an IllegalStateException: Response already committed in the server logs.

Categories