Suppose in a web applicaiton by Spring Mvc do we need to check for valid sessions in every controller or in jsps too? How can i solve this session management thing in MVC? What do we basically do? What are the other things which can add extra security to my application?
We usually check if session is expired in the filter layer and map it to the DispatcherServlet, this way, all the incoming request that will be handled by spring will be filtered first, and thus not allowing any interaction to a spring controller if session is already expired. If the session is found to be expired, send a redirect to a page where user will be informed that their session is already expired.
Sample Filter code
public class MyFilter implements Filter{
...
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (isSessionExpired((HttpServletRequest) theRequest)) {
response.sendRedirect(((HttpServletRequest) theRequest).getContextPath() + "/expired.jsp");
response.flushBuffer();
}else{
//..its not yet expired, continue
theChain.doFilter(theRequest, theResp);
}
}
...
}
Mapping to the DispatcherServlet in the web.xml
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>com.mycompany.ourproject.filter.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<servlet-name>springdispatcher</servlet-name>
</filter-mapping>
<servlet>
<servlet-name>springdispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With