public static < S extends HttpServlet > void doOptions ( HttpServletResponse response , Class < S > stopClass , Class < ? extends S > thisClass , String doGet , String doPost , String doPut , String doDelete , Class < ? > [ ] paramTypes ) { boolean ALLOW_GET = false ; boolean ALLOW_HEAD = false ; boolean ALLOW_POST = false ; boolean ALLOW_PUT = false ; boolean ALLOW_DELETE = false ; boolean ALLOW_TRACE = true ; boolean ALLOW_OPTIONS = true ; for ( Method method : getAllDeclaredMethods ( stopClass , thisClass ) ) { if ( Arrays . equals ( paramTypes , method . getParameterTypes ( ) ) ) { String methodName = method . getName ( ) ; if ( doGet . equals ( methodName ) ) { ALLOW_GET = true ; ALLOW_HEAD = true ; } else if ( doPost . equals ( methodName ) ) { ALLOW_POST = true ; } else if ( doPut . equals ( methodName ) ) { ALLOW_PUT = true ; } else if ( doDelete . equals ( methodName ) ) { ALLOW_DELETE = true ; } } } StringBuilder allow = new StringBuilder ( ) ; if ( ALLOW_GET ) { // if(allow.length() != 0) allow.append(", "); allow . append ( METHOD_GET ) ; } if ( ALLOW_HEAD ) { if ( allow . length ( ) != 0 ) allow . append ( ", " ) ; allow . append ( METHOD_HEAD ) ; } if ( ALLOW_POST ) { if ( allow . length ( ) != 0 ) allow . append ( ", " ) ; allow . append ( METHOD_POST ) ; } if ( ALLOW_PUT ) { if ( allow . length ( ) != 0 ) allow . append ( ", " ) ; allow . append ( METHOD_PUT ) ; } if ( ALLOW_DELETE ) { if ( allow . length ( ) != 0 ) allow . append ( ", " ) ; allow . append ( METHOD_DELETE ) ; } if ( ALLOW_TRACE ) { if ( allow . length ( ) != 0 ) allow . append ( ", " ) ; allow . append ( METHOD_TRACE ) ; } if ( ALLOW_OPTIONS ) { if ( allow . length ( ) != 0 ) allow . append ( ", " ) ; allow . append ( METHOD_OPTIONS ) ; } response . setHeader ( "Allow" , allow . toString ( ) ) ; }
A reusable doOptions implementation for servlets .