Spring Security With Web MVC Example

[Updated: Jul 7, 2017, Created: Jul 7, 2017]

In this example, we will learn how to use Spring security in a Spring Web MVC application. We will do in memory authentication of Spring security.

Maven dependencies



Java Config class

public class AppConfig extends WebSecurityConfigurerAdapter {

  public void configure(AuthenticationManagerBuilder builder)
          throws Exception {

  public ViewResolver viewResolver() {
      InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
      return viewResolver;

DispatcherServlet initializer

public class WebAppInitializer extends
      AbstractAnnotationConfigDispatcherServletInitializer {

  protected Class<?>[] getRootConfigClasses() {
      return new Class<?>[]{AppConfig.class};

  protected Class<?>[] getServletConfigClasses() {
      return null;

  protected String[] getServletMappings() {
      return new String[]{"/"};

Initializing Security components

We still need to extend AbstractSecurityWebApplicationInitializer to initialize the security filter.

public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {

A controller

public class ExampleController {
  public String handleRequest() {
      return "welcome to the app";

  public String handleRequest2(ModelMap map) {
      return "my-page";

The JSP page


<html lang="en">
<h2>Spring Security Example</h2>
<p>Time: ${time}</p>

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war


Accessing URI '/app' (Accessing any resource for the first time will show Spring authentication form):

After submitting user name and password as we set up in our AppConfig class:

Accessing URI '/page':

Example Project

Dependencies and Technologies Used:

  • spring-security-web 4.2.3.RELEASE: spring-security-web.
  • spring-security-config 4.2.3.RELEASE: spring-security-config.
  • spring-webmvc 4.3.9.RELEASE: Spring Web MVC.
  • javax.servlet-api 3.1.0 Java Servlet API
  • JDK 1.8
  • Maven 3.3.9

Spring Security with Web MVC Example Select All Download
  • spring-security-with-mvc-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp
          • WEB-INF
            • views

See Also