Invalidating session with CDI+JSF not working - session

I'm trying to implement a logout in my application, so I made this:
public String logout(){
try{
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext ex = facesContext .getExternalContext();
ex.invalidateSession();
return "success";
}catch(Exception e){
return "error";
}
}
But when I check if the user is logged, it says yes:
public class AuthenticateListener implements PhaseListener {
#Override
public void afterPhase(PhaseEvent event) {
AuthorizedUser authorized = (AuthorizedUser) Util.getHandler("authorized");
if (authorized.getUser() == null) {
System.out.println("Not Logged");
} else {
System.out.println("Logged");
}
}
#Override
public void beforePhase(PhaseEvent event) {
// TODO Auto-generated method stub
}
#Override
public PhaseId getPhaseId() {
return PhaseId.RESTORE_VIEW;
}
}
Am I missing something? Shouldn't I get a new instance of AuthorizedUser (sessionScoped) after invalidating my session?
EDIT: Adding the getHandler, if someone needs it ;)
public static Object getHandler(String handlerName) {
FacesContext facesContext = FacesContext.getCurrentInstance();
ELContext elContext = facesContext.getELContext();
ELResolver resolver = facesContext.getApplication().getELResolver();
Object uh = resolver.getValue(elContext, null, handlerName);
return uh;
}

The session is still available in the current request-response. It's not available anymore in the next request. You need to send a redirect after the invalidate so that the browser will be instructed to send a new request on the given URL.
return "success?faces-redirect=true";
Or if you're still using old fashioned navigation cases (the return values namely suggests that; it's strange to have a view with filename "success"), then add <redirect/> to the navigation case instead.
If that still doesn't work, then the bug is in how you're storing the user in session. For example, it's instead actually been stored in the application scope which may happen when you mix CDI #Named with JSF #SessionScoped, or when you assigned the logged-in user as a static variable instead of an instance variable.
See also:
How to invalidate session in JSF 2.0?
Performing user authentication in Java EE / JSF using j_security_check

Use this piece of code inside logout method:
HttpSession oldsession = (HttpSession) FacesContext
.getCurrentInstance().getExternalContext().getSession(false);
oldsession.invalidate();
This will work. Let me know please if it was helpful for you.

Related

Start a session from a given id in spring

How can I create a session in a spring mvc application from a given ID instead of a generated one?
I want to fixate the session.
The fixation will be started by a trusted ui service. This trusted service forwards all requests. Thus the fixation can't begin in browser. It is not intended to do it without this ui service.
Providing a HttpSessionIdResolver bean does not work, since it only changes the location in HTTP response. Eg Session ID in HTTP header after authorization.
Are there any solutions without creating a shadow session management?
Session is required for keycloak integration. Guess it's not possible to use keycloak in stateless mode.
Thanks in advance
It is possible to fixate a session with spring-session.
#Configuration
#EnableSpringHttpSession
public class SessionConfig {
#Bean
public HttpSessionIdResolver httpSessionIdResolver() {
return new HttpSessionIdResolver() {
public List<String> resolveSessionIds(HttpServletRequest request) {
final var sessionId = request.getHeader("X-SessionId");
request.setAttribute(SessionConfig.class.getName() + "SessionIdAttr", sessionId);
return List.of(sessionId);
}
public void setSessionId(HttpServletRequest request, HttpServletResponse response, String sessionId) {}
public void expireSession(HttpServletRequest request, HttpServletResponse response) {}
};
}
#Bean
public SessionRepository<MapSession> sessionRepository() {
return new MapSessionRepository(new HashMap<>()) {
#Override
public MapSession createSession() {
var sessionId =
(String)RequestContextHolder
.currentRequestAttributes()
.getAttribute(SessionConfig.class.getName()+"SessionIdAttr", 0);
final var session = super.createSession();
if (sessionId != null) {
session.setId(sessionId);
}
return session;
}
};
}
In #resolveSessionIds() you can read the ID and store for later use.
createSession() is called when no session has been found and a new one is required. Here you can create the session with previously remembered ID in MapSession#setId(String).
Even if is possible, IMO it is not a good idea. There might be other architectural solutions/problems.

How to implement Session Tracking in spring MVC?

I am very new to spring mvc, I have to develop a web application based on session tracking and my application is annotation based. In my web app I have route each page based on the username and role existence in session. Initially I have been using HttpSession as parameter to controller method, but it is very difficult to check each and every request. I know there are many application level security ways in spring, but I really couldn't understand how to use them. Please suggest me some solutions, For all help thanks in advance.
After updating with interceptors:
Controller class
// Method to showLogin page to user
#RequestMapping(value = "user")
public ModelAndView showLoginToUser(#ModelAttribute("VMFE") VmFeUser VMFE,HttpSession session) {
System.out.println("#C====>showLoginToUser()===> ");
ModelAndView view = new ModelAndView();
//session.setAttribute("user_name", "no_user");
try {
view.setViewName("login");
} catch (Exception e) {
e.printStackTrace();
}
return view;
}
Interceptor
public class HelloWorldInterceptor extends HandlerInterceptorAdapter {
#Override
public boolean preHandle (HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
RequestMapping rm = ((HandlerMethod) handler).getMethodAnnotation(
RequestMapping.class);
boolean alreadyLoggedIn = request.getSession()
.getAttribute("user_name") != null;
boolean loginPageRequested = rm != null && rm.value().length > 0
&& "login".equals(rm.value()[0]);
if (alreadyLoggedIn && loginPageRequested) {
//response.sendRedirect(request.getContextPath() + "/app/main-age");
return false;
} else if (!alreadyLoggedIn && !loginPageRequested) {
System.out.println("REDIRECTING===");
response.sendRedirect(request.getContextPath() + "/user");
return false;
}
return true;
}
}
Using spring security you can implement session tracking and apply filters to validate requests. Spring security is very easy to implement. Kindly follow spring security tutorial click here.
You can also check my git repo for implementation click here. It's a angular spring boot application and i have used spring security and JWT for authentication and authorization.
Hope it helps you thanks.

Spring security perform validations for custom login form

I need to do some validations on the login form before calling the authenticationManager for authentication. Have been able to achieve it with help from one existing post - How to make extra validation in Spring Security login form?
Could someone please suggest me whether I am following the correct approach or missing out something? Particularly, I was not very clear as to how to show the error messages.
In the filter I use validator to perform validations on the login field and in case there are errors, I throw an Exception (which extends AuthenticationException) and encapsulate the Errors object. A getErrors() method is provided to the exception class to retrieve the errors.
Since in case of any authentication exception, the failure handler stores the exception in the session, so in my controller, I check for the exception stored in the session and if the exception is there, fill the binding result with the errors object retrieved from the my custom exception (after checking runtime instance of AuthenticationException)
The following are my code snaps -
LoginFilter class
public class UsernamePasswordLoginAuthenticationFilter extends
UsernamePasswordAuthenticationFilter {
#Autowired
private Validator loginValidator;
/* (non-Javadoc)
* #see org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#attemptAuthentication(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
#Override
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
Login login = new Login();
login.setUserId(request.getParameter("userId"));
login.setPassword(request.getParameter("password"));
Errors errors = new BeanPropertyBindingResult(login, "login");
loginValidator.validate(login, errors);
if(errors.hasErrors()) {
throw new LoginAuthenticationValidationException("Authentication Validation Failure", errors);
}
return super.attemptAuthentication(request, response);
}
}
Controller
#Controller
public class LoginController {
#RequestMapping(value="/login", method = RequestMethod.GET)
public String loginPage(#ModelAttribute("login") Login login, BindingResult result, HttpServletRequest request) {
AuthenticationException excp = (AuthenticationException)
request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
if(excp != null) {
if (excp instanceof LoginAuthenticationValidationException) {
LoginAuthenticationValidationException loginExcp = (LoginAuthenticationValidationException) excp;
result.addAllErrors(loginExcp.getErrors());
}
}
return "login";
}
#ModelAttribute
public void initializeForm(ModelMap map) {
map.put("login", new Login());
}
This part in the controller to check for the instance of the Exception and then taking out the Errors object, does not look a clean approach. I am not sure whether this is the only way to handle it or someone has approached it in any other way? Please provide your suggestions.
Thanks!
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView signInPage(
#RequestParam(value = "error", required = false) String error,
#RequestParam(value = "logout", required = false) String logout) {
ModelAndView mav = new ModelAndView();
//Initially when you hit on login url then error and logout both null
if (error != null) {
mav.addObject("error", "Invalid username and password!");
}
if (logout != null) {
mav.addObject("msg", "You've been logged out successfully.");
}
mav.setViewName("login/login.jsp");
}
Now if in case login become unsuccessfull then it will again hit this url with error append in its url as in spring security file you set the failure url.
Spring security file: -authentication-failure-url="/login?error=1"
Then your URl become url/login?error=1
Then automatically signInPage method will call and with some error value.Now error is not null and you can set any string corresponding to url and we can show on jsp using these following tags:-
<c:if test="${not empty error}">
<div class="error">${error}</div>
</c:if>

How to design a session-less JSF 2.0 web application?

I am working on a JSF 2.0 website. The website has two kind of users(public and registered). Now I want to know that how can I create session for both kind of users? For registered users, when my user is login then there should be session for it, and when session expires then I redirect it to page that your session has expired. For public users there should be no session at all. Means there is no session time out for my public users and they never have messages that your session has expired. How can I implement this behavior in JSF 2.0.
Can I use filter for it or there is better approach for it? I also read that JSF automatically creates session using managed beans. Can I use these sessions for my task?
Edit:
I tell you what i did so you people better guide me in this scenerio
What i did i put a filter in my web app like this
<filter>
<filter-name>SessionTimeoutFilter</filter-name>
<filter-class>util.SessionTimeoutFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SessionTimeoutFilter</filter-name>
<url-pattern>*.xhtml</url-pattern>
</filter-mapping>
Here is my Filter code
public class SessionTimeoutFilter implements Filter {
// This should be your default Home or Login page
// "login.seam" if you use Jboss Seam otherwise "login.jsf"
// "login.xhtml" or whatever
private String timeoutPage = "faces/SessionExpire.xhtml";
private String welcomePage = "faces/index.xhtml";
public static Boolean expirePage = false;
private FilterConfig fc;
#Override
public void init(FilterConfig filterConfig) throws ServletException {
this.fc = filterConfig;
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
HttpSession session = httpServletRequest.getSession();
/**
* The session objects have a built-in data structure (a hash table) in which you can store
* any number of keys and associated values. You use session.getAttribute("key") to look up
* a previously stored value. The return type is Object, so you must do a typecast to
* whatever more specific type of data was associated with that attribute name in the session.
* The return value is null if there is no such attribute, so you need to check for null
* before calling methods on objects associated with sessions.
*
* Note:
* JSF session scoped managed beans are under the covers stored as a HttpSession
* attribute with the managed bean name as key.
*/
Login login = (Login)session.getAttribute("login");
if (login == null) { // No such object already in session
filterChain.doFilter(request, response);
} else {
/**
* If you use a RequestDispatcher, the target servlet/JSP receives the same
* request/response objects as the original servlet/JSP. Therefore, you can pass
* data between them using request.setAttribute(). With a sendRedirect(), it is a
* new request from the client, and the only way to pass data is through the session or
* with web parameters (url?name=value).
*/
filterChain.doFilter(request, response);
}
System.out.println();
} //end of doFilter()
#Override
public void destroy() {
} //end of destroy()
Now what happen that if you first time enter url of my site then this filter invoke. It gets
Login login = (Login)session.getAttribute("login");
null. So it simply move to my index.xhtml page. Now my index.html page constructor invokes. Here is my code
#ManagedBean
//////#RequestScoped
#SessionScoped
public class Login implements Serializable {
//Constructor
public Login() {
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
//getSession(false), which returns null if no session already exists for the current client.
HttpSession session =(HttpSession)externalContext.getSession(false);
if (session == null) {
System.out.println();
} else {
session.setAttribute("logedin", 0); //public user
session.setMaxInactiveInterval(-1); // no session time out
Enumeration e = session.getAttributeNames();
while (e.hasMoreElements()) {
/**
* Here you also get "login" attr. Because when managed bean create the
* session, it sets you managedBean name in the session attribute.
*/
String attr = (String)e.nextElement();
System.err.println("attr = "+ attr);
Object value = session.getAttribute(attr);
System.err.println("value = "+ value);
} //end of while
}
}//end of constructor
} //end of class Login
when first time user come to my site then it is not login so i set logedin session attribute 0. Now suppose user enter credentials and press log in button. First my filter is invoke but this time it will get login attribute and comes to my doFilter() else check and then come to My validUser() method. Here is my code
public String validUser() throws Exception {
ArrayList2d<Object> mainarray = new ArrayList2d<Object>();
mainarray.addRow();
mainarray.add(userName);
mainarray.add(password);
busBeans.usermanagement.users um = new busBeans.usermanagement.users();
ArrayList retrieveList = um.getValidUser(mainarray); //database check of user existence
if (Integer.parseInt(retrieveList.get(0).toString()) == 0) {
ArrayList str = (ArrayList) retrieveList.get(1);
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
//getSession(false), which returns null if no session already exists for the current client.
HttpSession session =(HttpSession)externalContext.getSession(false);
if (session == null) {
System.out.println();
} else {
Enumeration e = session.getAttributeNames();
while (e.hasMoreElements()) {
String attr = (String)e.nextElement();
System.err.println("attr = "+ attr);
Object value = session.getAttribute(attr);
System.err.println("value = "+ value);
} //end of while
}
logedin=true;
session.setAttribute("logedin", 1);
session.setAttribute("firstLastName", str.get(7).toString());
session.setAttribute("getusercredentials", str);
session.setAttribute("sessionUserId", str.get(0).toString());
session.setAttribute("sessionRoleId",str.get(1).toString());
firstLastName = session.getAttribute("firstLastName").toString();
session.setMaxInactiveInterval(60); //1 min
ConnectionUtil.setRgihts(Integer.parseInt(str.get(0).toString()) , Integer.parseInt(str.get(1).toString()) ,Integer.parseInt(str.get(5).toString()));
checkRgihts();
}
} //end of validUser()
Now i want to ask one thing. I set sessionTimeout using setMaxInterval. Is it ok or it is better to do in web.xml? Now whne timeOut expires then filter doesn't invoke. But suppose that I also attach HttpSessionListener. Then on session time Out its destroy method invoke. I can invalidate session here. Like this.
public class MySessionListener implements HttpSessionListener {
// Constructor
public MySessionListener() {
} //end of constructor
#Override
public void sessionCreated(HttpSessionEvent event) {
System.out.println("Current Session created : " + event.getSession().getCreationTime());
System.out.println();
} //end of sessionCreated()
#Override
public void sessionDestroyed(HttpSessionEvent event) {
// get the destroying session...
HttpSession session = event.getSession();
if (session != null) {
session.invalidate();
}
System.out.println();
} //end of sessionDestroyed()
} //end of class MySessionListener
But on session expiration i also want to redirect user to redirecr Page if this is a registered user. IF this is a public user i don't want to redirect it although session has expired. I can check in the destroy method by getting attribute logedin that it is a public user or registered user. But then how can i redirect for registered user or do nothing for public user.
If somehow my filter invoke on session time out and some how i check that if this is a registered user by getting logedin attribute 1 and session time out has expired, because for public user i set timeout -1, then redirect the user, using RequestDispatcher otherwoise do filterChain.doFilter(request, response);.
So this is the scenerio that i implemented. I don't know whether my approaches are right or not ? I don't know what security issues i will face by this approach. So that's it.. Now you people guide me what should i do.....
Thanks
I understand what your goal is, but I don't think that not having a Session for unauthenticated users is particularly the best approach.
Consider an unauthenticated user navigating through a Primefaces wizard as he provides information to sign up for an account, (Eg. Pick Username, Provide Password, Choose Security Questions, etc...)
You are not going to want to persist this user information until it all has been collected and validated, because perhaps the user has a change of heart and decides not to sign up? Now you have an incomplete user record in your database that needs to be cleaned.
The answer is that you need to store this information in a ViewScoped bean or in session until the unauthenticated user confirms the account creation, where it can finally be persisted.
What I feel the best approach would be is for you to give a User a unique Role with one role being Unauthenticated. Using components like Spring Security 3 or even Seam you should be able to control page Authorization through the Role of the User in Session.
For instance, you can prevent unauthenticated users from entering pages in ../app/* or normal users from accessing pages in ../admin/*
I used some thing like this. First there is a filter. Here is my filter
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
//Send request to server after each 1min
// httpServletResponse.setIntHeader("Refresh", 60);
//getSession(false), which returns null if no session already exists for the current client
HttpSession session = httpServletRequest.getSession(false);
if (session == null) {
//session timeout check.
if (httpServletRequest.getRequestedSessionId() != null && !httpServletRequest.isRequestedSessionIdValid()) {
System.out.println("Session has expired");
/**
* getSession() (or, equivalently, getSession(true)) creates a new session if no
* session already exists.
*/
session = httpServletRequest.getSession(true);
session.setAttribute("logedin", "0"); // public user
//httpServletResponse.sendRedirect("http://www.google.com");
httpServletResponse.sendRedirect(timeoutPage);
} else {
session = httpServletRequest.getSession(true);
session.setAttribute("logedin", "0");
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
} else {
String isRegisteredUser = session.getAttribute("logedin").toString();
if (isRegisteredUser.equalsIgnoreCase(("1"))) {
Login login = (Login)session.getAttribute("login");
Enumeration e = session.getAttributeNames();
System.out.println("");
filterChain.doFilter(httpServletRequest, httpServletResponse);
} else if (isRegisteredUser.equalsIgnoreCase(("0"))) {
Enumeration e = session.getAttributeNames();
filterChain.doFilter(httpServletRequest, httpServletResponse);
} //end of else if (isRegisteredUser.equalsIgnoreCase(("0")))
}
} //end of doFilter()
Now when user enter url of my site then this filter invoke. First time it get session null then it checks for session timeout. no session time out so it creates a session. Set logedin attribute to zero, means this is public user and pass the request. Here is my method
//constructor
public Login() {
try {
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpServletRequest httpServletRequest = (HttpServletRequest)externalContext.getRequest();
//getSession(false), which returns null if no session already exists for the current client.
HttpSession session =(HttpSession)externalContext.getSession(false);
if (session == null) {
session = httpServletRequest.getSession(true);
session.setAttribute("logedin", "0");
session.setMaxInactiveInterval(-1);
System.out.println();
} else {
session.setAttribute("logedin", "0");
//No session timeout for public users
session.setMaxInactiveInterval(-1);
Enumeration e = session.getAttributeNames();
}
} catch (Exception e) {
System.out.println("Exception in session " + e.getMessage());
}
} //end of constructor
First time it gets session, just override the values so there is no harm to set the same attribute. But here i just want to ask one thing that is it ok to set no session time out for public users ? will it damage my application at some point, like my server goes out of memory and etc ? If yes, then how can i overcome this ?
Now suppose that my user is log in. Then my filter invoke, this time it will get a session so it comes to my isRegisterdUser check and check the value. He get 0 , just pass the request and then my valid user method call.
public String validUser() throws Exception {
String returnString = null;
ArrayList2d<Object> mainarray = new ArrayList2d<Object>();
mainarray.addRow();
mainarray.add(userName);
mainarray.add(password);
busBeans.usermanagement.users um = new busBeans.usermanagement.users();
ArrayList retrieveList = um.getValidUser(mainarray);
if (Integer.parseInt(retrieveList.get(0).toString()) == 0) {
ArrayList str = (ArrayList) retrieveList.get(1);
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
//getSession(false), which returns null if no session already exists for the current client.
HttpSession session =(HttpSession)externalContext.getSession(false);
if (session == null) {
System.out.println();
} else {
Enumeration e = session.getAttributeNames();
}
System.out.println();
logedin=true;
//Set session attributes for login users
session.setAttribute("logedin", 1);
session.setAttribute("firstLastName", str.get(7).toString());
session.setAttribute("getusercredentials", str);
session.setAttribute("sessionUserId", str.get(0).toString());
session.setAttribute("sessionRoleId",str.get(1).toString());
session.setAttribute("registeredUser", "true");
/**
* set session timeout for login user
* 1 min = 60 sec
* 5 min = 60 * 5 sec = 300 sec
*/
session.setMaxInactiveInterval(300); //5min
firstLastName = session.getAttribute("firstLastName").toString();
}
return returnString=null;
} //end of validUser()
I override the value of logedin attribute to 1 so now the user become valid user. Now if valid user make request then my filter invoke, it will get a session so it comes to my isRegisterdUser check, this time it get value 1 so just pass the request.Now when session time out and user make any request, then my filter invoke and this time it comes inside the check
if (httpServletRequest.getRequestedSessionId() != null && !httpServletRequest.isRequestedSessionIdValid()) {
System.out.println("Session has expired");
//httpServletResponse.sendRedirect("http://www.google.com");
httpServletResponse.sendRedirect(timeoutPage);
} else {
session = httpServletRequest.getSession(true);
session.setAttribute("logedin", "0");
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
and redirect the user by making it public. So here how this i do it. I got also a idea that i refresh the page after some time, i have sessionCreationTime, sessionLastAccessTime and sessionMaxTime. so i can do a work like this
String isRegisteredUser = session.getAttribute("logedin").toString();
if (isRegisteredUser.equalsIgnoreCase(("1"))) {
Login login = (Login)session.getAttribute("login");
Enumeration e = session.getAttributeNames();
while (e.hasMoreElements()) {
String attr = (String)e.nextElement();
System.err.println("attr = "+ attr);
Object value = session.getAttribute(attr);
System.err.println("value = "+ value);
} //end of while
long sessionCreationTime = session.getCreationTime();
int sessionCreationTimeInSec = (int)(sessionCreationTime / 1000) % 60;
int sessionCreationTimeInMinutes = (int)((sessionCreationTime / (1000*60)) % 60);
long sessionLastAccessTime = session.getLastAccessedTime();
int sessionLastAccessTimeInSec = (int)(sessionLastAccessTime / 1000) % 60 ;
int sessionLastAccessTimeInMinutes = (int)((sessionLastAccessTime / (1000*60)) % 60 );
int sessionMaxTime = session.getMaxInactiveInterval();
int sessionMaxTimeInMinute = sessionMaxTime / 60 ;
if ((sessionCreationTimeInMinutes - sessionLastAccessTimeInMinutes) - 1 > sessionMaxTimeInMinute) {
System.out.println("Session is expiring in one minute");
}
System.out.println("");
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
The idea here is that if some how you check that how much time left for session timeout then you can invalidate the session just before your session time out time. Because once your session expire you get session null and you have no attributes to check. But before one minute you have session and all session attributes so you can do whatever you want. I don't know how solid idea is this, it's just an approach that came to my mind.
Also suppose user is login and then suddenly closed the browser. Closing browser close the session. Now when you open your browser then you get a message that your session has expire. I want to ask when you open a browser can i use this check
if (httpServletRequest.getRequestedSessionId() != null && !httpServletRequest.isRequestedSessionIdValid()) {
System.out.println("Session has expired");
if (session.isNew()) {
/**
* getSession() (or, equivalently, getSession(true)) creates a new session if no
* session already exists.
*/
session = httpServletRequest.getSession(true);
session.setAttribute("logedin", "0"); // public user
filterChain.doFilter(httpServletRequest, httpServletResponse);
} else {
httpServletResponse.sendRedirect("http://www.google.com");
}
}
I used isNew() check because i want to do that if user is entering your site first time, like open his browser, then he didn't see the redirection message although his session has been expired because of closing browser.
Thanks

Spring 3.0 RESTful Controller Fails on Redirect

I am setting up a simple RESTful controller for a Todo resource with an XML representation. It all works great - until I try to redirect. For example, when I POST a new Todo and attempt to redirect to its new URL (for example /todos/5, I get the following error:
Error 500 Unable to locate object to be marshalled in model: {}
I do know the POST worked because I can manually go to the new URL (/todos/5) and see the newly created resource. Its only when trying to redirect that I get the failure. I know in my example I could just return the newly created Todo object, but I have other cases where a redirect makes sense. The error looks like a marshaling problem, but like I said, it only rears itself when I add redirects to my RESTful methods, and does not occur if manually hitting the URL I am redirecting to.
A snippet of the code:
#Controller
#RequestMapping("/todos")
public class TodoController {
#RequestMapping(value="/{id}", method=GET)
public Todo getTodo(#PathVariable long id) {
return todoRepository.findById(id);
}
#RequestMapping(method=POST)
public String newTodo(#RequestBody Todo todo) {
todoRepository.save(todo); // generates and sets the ID on the todo object
return "redirect:/todos/" + todo.getId();
}
... more methods ...
public void setTodoRepository(TodoRepository todoRepository) {
this.todoRepository = todoRepository;
}
private TodoRepository todoRepository;
}
Can you spot what I am missing? I am suspecting it may have something to do with returning a redirect string - perhaps instead of it triggering a redirect it is actually being passed to the XML marshaling view used by my view resolver (not shown - but typical of all the online examples), and JAXB (the configured OXM tool) doesn't know what to do with it. Just a guess...
Thanks in advance.
This happend because redirect: prefix is handled by InternalResourceViewResolver (actually, by UrlBasedViewResolver). So, if you don't have InternalResourceViewResolver or your request doesn't get into it during view resolution process, redirect is not handled.
To solve it, you can either return a RedirectView from your controller method, or add a custom view resolver for handling redirects:
public class RedirectViewResolver implements ViewResolver, Ordered {
private int order = Integer.MIN_VALUE;
public View resolveViewName(String viewName, Locale arg1) throws Exception {
if (viewName.startsWith(UrlBasedViewResolver.REDIRECT_URL_PREFIX)) {
String redirectUrl = viewName.substring(UrlBasedViewResolver.REDIRECT_URL_PREFIX.length());
return new RedirectView(redirectUrl, true);
}
return null;
}
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
}
}

Resources