Simple Login Form with Spring MVC and Interceptor

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}.
	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")) {
				return false;

		return true;


2. Register your interceptor class in your webapp config class

@ComponentScan(basePackages = "com.sample")
public class AppConfig extends WebMvcConfigurerAdapter {

	private org.apache.commons.configuration.Configuration _config = ConfigManager.getConfiguration();

	public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {

	public void addResourceHandlers(ResourceHandlerRegistry registry) {

	public void addInterceptors(InterceptorRegistry registry) {
		UIinterceptor interceptor = new UIinterceptor();

3. Add method login GET (to showing login page) , login POST (to cater username and password), and logout (to invalidate session)

@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();
		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">
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
<title>System Authentication</title>
	<h3>System Authentication</h3>
	<form action="/ui/login" method="POST">
					<input type="text" name="username" />
					<input type="password" name="password" />
				<td colspan="3">
					<input type="submit" value="Submit" />

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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>