Session Checking with Filter and Redirecting
10,522
Do not continue with filter after doing sendRedirect
. sendRedirect
will commit the headers to the client and after that you are not supposed to write anything.
And have the login.jsp to your allowed url's.
if (!allowedRequest) {
HttpSession session = request.getSession(false);
if (null == session || ) {
response.sendRedirect("Login.jsp");
return;
}
}
References:
Cause of Servlet's 'Response Already Committed'
Author by
Ravi Dutt
Updated on June 04, 2022Comments
-
Ravi Dutt almost 2 years
I am trying to do login operation but when I am using filter for checking whether session is valid or not then I got the exception as :-
java.lang.IllegalStateException
, Cannot create a session after the response has been committed .Myservlet filter code is :-
public class SessionFilter implements javax.servlet.Filter { private ArrayList<String> urlList; public void destroy() { } public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; String url = request.getServletPath(); boolean allowedRequest = false; if(urlList.contains(url)) { allowedRequest = true; } if (!allowedRequest) { HttpSession session = request.getSession(false); if (null == session) { response.sendRedirect("Login.jsp"); } } chain.doFilter(req, res); } public void init(FilterConfig fConfig) throws ServletException { String urls = fConfig.getInitParameter("avoid-urls"); //StringTokenizer token = new StringTokenizer(urls, ","); StringTokenizer token = new StringTokenizer(urls); urlList = new ArrayList<String>(); urlList.add(token.nextToken()); /*while (token.hasMoreTokens()) { urlList.add(token.nextToken()); }*/ } } Filter mapping in web.xml is :- <filter> <filter-name>SessionFilter</filter-name> <filter-class>Filter.SessionFilter</filter-class> <init-param> <param-name>avoid-urls</param-name> <param-value>Login.jsp,</param-value> </init-param> </filter> <filter-mapping> <filter-name>SessionFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
Now when I requests for
login.jsp
then i got the this exception . Please help i am getting stuck on my project since last 2 days here. -
Vikas V about 11 yearsThis solution was provided to OP in my comments. But, OP says it doesn't work.