Last Updated: February 25, 2016
·
1.311K
· fbecart

Implement HTTP method OPTIONS in Spring MVC 3.2.1

package com.fbecart.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import com.google.common.base.Joiner;

@SuppressWarnings("serial")
public class CustomDispatcherServlet extends DispatcherServlet {
  private RequestMappingHandlerMapping requestMappingHandlerMapping;

  @Override
  protected void onRefresh(ApplicationContext context) {
    super.onRefresh(context);
    requestMappingHandlerMapping = context.getBean(RequestMappingHandlerMapping.class);
  }

  @Override
  protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException,
      IOException {
    try {
      requestMappingHandlerMapping.getHandler(request);
      super.doOptions(request, response);
    } catch (HttpRequestMethodNotSupportedException e) {
      response.setHeader("Allow", Joiner.on(',').join(e.getSupportedHttpMethods()));
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
}