com.tamnd.app.init.WebMvcInitializer.java Source code

Java tutorial

Introduction

Here is the source code for com.tamnd.app.init.WebMvcInitializer.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tamnd.app.init;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.DispatcherServlet;

/**
 *
 * @author tamnd
 */
public class WebMvcInitializer implements WebApplicationInitializer {

    private static final String MAPPING_URL = "/";
    private static final String CONF_LOCATION = "com.tamnd.app.config";

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        // Create the 'root' Spring application context
        WebApplicationContext context = context();

        // Manage the lifecycle of the root application context
        servletContext.addListener(new ContextLoaderListener(context));

        DispatcherServlet dispatcherServlet = new DispatcherServlet(context);
        dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);

        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcherServlet", dispatcherServlet);
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping(MAPPING_URL);

        servletContext
                .addFilter("securityFilter",
                        new DelegatingFilterProxy("springSecurityFilterChain"/*Do not change this name*/))
                .addMappingForUrlPatterns(null, false, "/*");
        //      servletContext.addFilter("hibernateFilter", new OpenSessionInViewFilter())
        //            .addMappingForUrlPatterns(null, false, "/*");
    }

    private AnnotationConfigWebApplicationContext context() {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.setConfigLocation(CONF_LOCATION);
        return context;
    }
}