#Override
public void sessionDestroyed(HttpSessionEvent arg0)
{
boolean isRemoved = sessionIdSet.remove(arg0.getSession().getId());
if (isRemoved)
{
arg0.getSession().invalidate();
System.out.println(arg0.getSession().getAttribute("userName"));
System.out.println("session destroyed");
}
}
Suppose the attribute userName was testUser at the time of login. So after timeout in my java console I get null and session destroyed printed. So if it is null that means when I do following in my jsp I should get null but instead still I get testUser
$("body").click(function(event){
var property="<%=session.getAttribute("userName")%>";
//Here I expect property to be null as session is destroyed
//and it prints null in java so it should also here.
alert(property);
//But what i get here is testUser
}
Using Spring interceptor
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException {
boolean allowRequest = true;
String requestUri = request.getRequestURI().toString();
HttpSession session = request.getSession(false);
logger.info("Pre-intercepting request URI: " + requestUri);
try {
if(null != session) {
String sessionBelongsTo = (String) session.getAttribute("CUR_TYPE");
String user = (String) session.getAttribute("userName");
System.out.println(user);
if(!requestUri.endsWith("/login") && !requestUri.endsWith("/loginauth") && !requestUri.endsWith("sap-ui-core.js") && !requestUri.endsWith("/main")) {
if(null == user) {
logger.info(""
+ "Login required, redirecting to LOGIN page");
response.sendRedirect(request.getContextPath() + "/login");
allowRequest = false;
}
else {
logger.info("Login not required");
}
}
}
else{
logger.debug("session is null.redirecting to login");
session = request.getSession();
response.sendRedirect(request.getContextPath() + "/login");
allowRequest = false;
}
}catch(IOException ioe) {
logger.info(ioe.getMessage());
allowRequest = false;
}
return allowRequest;
}
Using interceptor makes an redirect call GET http://localhost:9090/app/login which is successfull but redirect never really happens.
You are mixing two different codes. You have to realize, where and when each code is executed - JSP on the server when the page is requested and rendered (i.e. before the response is send to the browser) and Javascript in the browser, after the browser receives the already generated response.
I.e. <%=session.getAttribute("userName")%> is processed on the server, and your browser receives e.g. var property="johndoe"; - the JSP code is NOT executed again when your onclick handler is executed.
Related
Can I know how can I get the session object which I have set in one controller method to another controller method.
Code:
public ResponseEntity<String> generateId(#RequestBody IdCreationVO idCreationVO, HttpServletRequest request) throws CareBusinessServiceException {
log.info("In Controller Method: generateId : "+idCreationVO.toString());
if(null !=idCreationVO && null == idCreationVO.getIsSupressCommunication()) {
HttpSession session = request.getSession();
session.setAttribute(AmhiConstants.COMMUNICATION_SUPPRESSED, idCreationVO.getIsSupressCommunication());
log.info("session object communication: "+ idCreationVO.getIsSupressCommunication());
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
return new ResponseEntity(idCreationService.generateId(idCreationVO), headers,
HttpStatus.OK);
}
public ResponseEntity<String> updateAuthorizationDetails(#RequestBody AuthorizationVO authorizationVO, HttpServletRequest request) throws CareBusinessServiceException {
String communicationSuppressed = null;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
String authNbrResponse = idCreationService.updateAuthorizationDetails(authorizationVO);
if(null != request.getSession()) {
communicationSuppressed = (String) request.getSession().getAttribute(AmhiConstants.COMMUNICATION_SUPPRESSED);
log.info("communicationSuppressed value: "+ communicationSuppressed);
}
/** This method is get triggered from controller as the communication registered functionality get excecuted before updateAuthorizationDetails ends **/
if (null != authNbrResponse && communicationSuppressed.equals(AmhiConstants.CONSTANT_Y)) {
String[] authorizationNumber = authNbrResponse.split(":");
if (authorizationNumber.length > 1) {
if (authorizationNumber[1].equalsIgnoreCase(AmhiConstants.STATUS_SUCCESS)) {
idCreationService.triggercommunicationAfterAuthorizationRegistered(authorizationNumber[0]);
}
}
}
return new ResponseEntity(authNbrResponse, headers,
HttpStatus.OK);
}
As per requirement I need the value which been sent in generateId method to be get used in updateAuthorizationDetails method.
Can I know the above code implementation works fine in user session?
session.setAttribute and session.getAttribute methods should work.
But the problem seems to be in the if condition:
if(null !=idCreationVO && null == idCreationVO.getIsSupressCommunication()) {
HttpSession session = request.getSession();
session.setAttribute(AmhiConstants.COMMUNICATION_SUPPRESSED, idCreationVO.getIsSupressCommunication());
log.info("session object communication: "+ idCreationVO.getIsSupressCommunication());
}
It checks whether idCreationVO.getIsSupressCommunication() is null and then sets it to the session. In other words, it only sets the variable to the session when it is null.
I guess you mean:
if(null !=idCreationVO && null != idCreationVO.getIsSupressCommunication()) {
HttpSession session = request.getSession();
session.setAttribute(AmhiConstants.COMMUNICATION_SUPPRESSED, idCreationVO.getIsSupressCommunication());
log.info("session object communication: "+ idCreationVO.getIsSupressCommunication());
}
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));
I have a servlet like the following
public class Ticket extends HttpServlet {
private static final long serialVersionUID = 1L;
public Ticket() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// check cookies
Cookie[] receivedCookies = request.getCookies();
if(receivedCookies != null){
Cookie user = receivedCookies[0];
response.getWriter().println("user: " + user.getValue());
response.addCookie(user);
// check session
HttpSession session = request.getSession(true);
Object atribVal = session.getAttribute(user.getValue()); // get a current state
if(atribVal == null){
response.getWriter().println("current state: null");
}
else{
response.getWriter().println("current state: " + atribVal.toString());
}
String newState = TicketMachine.getNextState(atribVal); // get a new state based on the current one
response.getWriter().println("new state: " + newState);
if(newState == "COMPLETED"){ // ticket completed, destroy session
session.invalidate();
return;
}
else{ // move to the next state
session.setAttribute(user.getValue(), newState);
}
}
}
}
I am trying to store a state of a ticket machine for each user who requests a ticket. I'm running this on Oracle WebLogic Server and testing it using cURL get requests that looks like the following
curl --cookie "user=John" 127.0.0.1:7001/myApp/Ticket
I would expect it to move through states as they are defined in the state machine, but it always returns the same lines
user: John
current state: null
new state: NEW
The ticket machine is quite simple
public class TicketMachine {
public static String getNextState(Object currentState){
if(currentState == null)
return "NEW";
switch(currentState.toString()){
case "NEW":
return "PAYMENT";
case "PAYMENT":
return "COMPLETED";
}
return null;
}
}
What am I doing wrong here?
When session is created it adds to response cookies session parameters such as session id. Your command to cURL does not stores cookies from server. You have to store cookies as follows curl --cookie oldcookies.txt --cookie-jar newcookies.txt http://www.example.com.
Also read section about cookies at http://curl.haxx.se/docs/httpscripting.html
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
I need to get current session Id without hitting the session (to give it a chance to expire).
I've used Cookies from Servlet code in order keep the session not-touched and then make the session expires after its timeout time.
I am using the following code:
public static String getSessionId(HttpServletRequest request)
{
String sessionId = "";
String logMsg = "";
if (request != null)
{
String sessionTimeout = PropertiesReader.SESSION_TIMEOUT_SCHEMA;
if (sessionTimeout != null && SessionHelper.SESSION_TIMEOUT_FIXED.equalsIgnoreCase(sessionTimeout))
{
logMsg = "FIXED: Getting SessionId from Cookies with activating the session";
Cookie[] cookies = request.getCookies();
if (cookies != null)
{
for (Cookie cook : cookies)
{
if ("JSESSIONID".equalsIgnoreCase(cook.getName()))
{
sessionId = cook.getValue();
break;
}
}
}
} else
{
logMsg = "PER_USAGE: Getting SessionId from Session";
sessionId = request.getSession(false) != null ? request.getSession(false).getId() : "";
}
}else
{
logMsg = "Request object is null";
}
logger.info(logMsg + ", sessionId=" + sessionId);
return sessionId;
}
One one OC4J app server, it works fine. although on another oc4j server, the code of accessing cookies makes the session keep active and don't timeout!
EDIT:
I really stucked!, I've trying to place afilter to remove the JSESSIONID cookie and remove all cookies from the HttpServletRequest, but when I call getSession(false) on the request passed to the servlet, I got a valid Session!
class CookieRemovalHttpServletRequestWrapper extends HttpServletRequestWrapper
{
public static final String COOKIE_HEADER = "cookie";
public static final String JSESSIONID = "JSESSIONID";
public CookieRemovalHttpServletRequestWrapper(HttpServletRequest request)
{
super(request);
}
#Override
public String getHeader(String name)
{
if (COOKIE_HEADER.equalsIgnoreCase(name))
{
return "";
}
return super.getHeader(name);
}
#Override
public Enumeration getHeaderNames()
{
Enumeration e = super.getHeaderNames();
List l = new ArrayList();
while (e.hasMoreElements())
{
String headerName = (String) e.nextElement();
if (!COOKIE_HEADER.equalsIgnoreCase(headerName))
{
l.add(headerName);
}
}
return Collections.enumeration(l);
}
#Override
public Enumeration getHeaders(String name)
{
if (COOKIE_HEADER.equalsIgnoreCase(name))
{
return new Enumeration()
{
public boolean hasMoreElements()
{
return false;
}
public Object nextElement()
{
return null;
}
};
}
return super.getHeaders(name);
}
#Override
public Cookie[] getCookies()
{
Cookie[] cs = super.getCookies();
List<Cookie> cokRet = new ArrayList<Cookie>(cs.length);
for (Cookie c : cs)
{
if (c.getName().equalsIgnoreCase(JSESSIONID)) continue;
cokRet.add(c);
}
return cokRet.toArray(new Cookie[] {});
}
}
And really think to forget all about Session and just use the session Id as just a unique identifier to the user, and do it myself the hard way.
As to your code, don't do it the hard way, use HttpServletRequest#getRequestedSessionId() and HttpServletRequest#isRequestedSessionIdValid() instead to check the requested session ID and if it is valid.
if (request.getRequestedSessionId() != null && !request.isRequestedSessionIdValid()) {
// The session has been expired (or a hacker supplied a fake cookie).
}
As to your concrete problem:
the code of accessing cookies makes the session keep active and don't timeout!
No, the code doesn't do that. It's the HTTP request itself which does that. It is not true that whenever you don't call getSession() or something, the session timeout won't be postponed. It will be postponed on every single HTTP request fired by the client, regardless of whether you need the session in the code.
To learn about how sessions work, you may find this answer helpful: How do servlets work? Instantiation, sessions, shared variables and multithreading
The session expiring isn't dependent on your code accessing the session, it depends on the user making a request with that session. Every time the user makes a request, the session's timeout will reset itself.
If you want to not have the user's request re-set the timeout (ie. have a fixed-length session), then you will need to do additional things for configuring the session, including possibly using a different filter to handle sessions.
The session is not timeout, that is correct behavior, because request was accepted and session expiration is updated in any case.