SpringMVC provides Interceptors which can be used to intercept the URL and pre-process, post-process the requests.
Let us write a simple AuthenticationInterceptor to check whether the user is already logged in or not. If the User is already logged into the system we will let him continue otherwise we will redirect him to login page.
AuthenticationInterceptor .java
package com.sivalabs.web.controllers; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import com.sivalabs.entities.User; @Component public class AuthenticationInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String uri = request.getRequestURI(); if(!uri.endsWith("login.do") && !uri.endsWith("logout.do")) { User userData = (User) request.getSession().getAttribute("LOGGEDIN_USER"); if(userData == null) { response.sendRedirect("login.do"); return false; } } return true; } }
LoginController.java
package com.sivalabs.web.controllers; @Controller public class LoginController { @RequestMapping(value="/login", method=RequestMethod.POST) public ModelAndView login(@ModelAttribute("login")User user, BindingResult result, SessionStatus status, HttpServletRequest request) { String viewName = "login"; ModelAndView mav = new ModelAndView(viewName); loginFormValidator.validate(user, result); if (result.hasErrors()) { return mav; } User userData = userService.login(user); status.setComplete(); if(userData == null){ mav.getModel().put("ERROR", "Invalid UserName and Password"); }else{ viewName = "welcome"; request.getSession().setAttribute("LOGGEDIN_USER", userData); } mav.setViewName(viewName); return mav; } }
WEB-INF/dispatcher-servlet.xml
<context:annotation-config/> <context:component-scan base-package="com.sivalabs"/> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"/> <ref bean="authenticationInterceptor"/>
Now if we try to access any other URLs without logging into the application it will automatically redirect to login page.
Good Articale
ReplyDeletehttp://javacircuit.blogspot.com
WEB-INF/dispatcher-servlet.xml is little bit confusing..
ReplyDeletecan u suggest where should I place
ReplyDeleteWhat i have to do if some one remove this from serviet.xml file. Application will run without authentication.