Hi everyone in this post I just want to show you on how to create a simple form login with Spring MVC and Interceptor (without additional security framework). Do not practice this tutorial to your complex project, it’s a just snippet code to make simple system authentication and you don’t have to add additional security framework dependency. To see how it works, let us see below codes :
1. Create an Interceptor class to intercept every single URL requested except login URL itself.
package com.sample.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.springframework.util.StringUtils; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import com.sample.utils.Constants; public class UIinterceptor extends HandlerInterceptorAdapter { private final Logger log = Logger.getLogger(getClass()); /** * This implementation always returns {@code true}. */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(); String user = (String) session.getAttribute(Constants.USER_SESSION); if( !request.getRequestURI().equals("/ui/login")) { if(StringUtils.isEmpty(user)){ response.sendRedirect("/ui/login"); return false; } } return true; } }
2. Register your interceptor class in your webapp config class
@Configuration @EnableWebMvc @ComponentScan(basePackages = "com.sample") public class AppConfig extends WebMvcConfigurerAdapter { private org.apache.commons.configuration.Configuration _config = ConfigManager.getConfiguration(); @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); }; @Override public void addInterceptors(InterceptorRegistry registry) { UIinterceptor interceptor = new UIinterceptor(); registry.addInterceptor(interceptor).addPathPatterns("/ui/**"); } }
3. Add method login GET (to showing login page) , login POST (to cater username and password), and logout (to invalidate session)
@Controller @RequestMapping(value = "/ui") public class UIController extends BaseController { @RequestMapping(value = "/login", method = RequestMethod.GET) public String loginHandler()throws Exception { return "/ui/login"; } @RequestMapping(value = "/login", method = RequestMethod.POST) public String loginHandlerPost()throws Exception { String username = getRequest().getParameter("username"); String password = getRequest().getParameter("password"); if(username.equals("yourUsername") && password.equals("yourPassword")) { HttpSession session = getRequest().getSession(); session.setAttribute(Constants.USER_SESSION, username); } return "redirect:/ui"; } @RequestMapping(value = "/logout", method = RequestMethod.GET) public String logoutHandler() throws Exception { HttpSession session = getRequest().getSession(); session.invalidate(); return "redirect:/ui"; } }
4. and the last login page itself.
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" language="java" %> <%@ include file="taglibs.jsp"%> <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' /> <title>System Authentication</title> </head> <body> <h3>System Authentication</h3> <form action="/ui/login" method="POST"> <table> <tr> <td>Username</td> <td>:</td> <td> <input type="text" name="username" /> </td> </tr> <tr> <td>Password</td> <td>:</td> <td> <input type="password" name="password" /> </td> </tr> <tr> <td colspan="3"> <input type="submit" value="Submit" /> </td> </tr> </table> </form> </body> </html>
The thing is interceptor will check for every single URL requested, if HTTPÂ Session exist it will continue and it doesn’t exist system will be redirected to login page. In this page you have to provide username and password if username and password is correct then HTTP Session will be created, so interceptor will always allow your request after login. HTTP Session will be invalidated when user is logout. That’s all