private void addDispatcherContext(ServletContext container) { // Create the dispatcher servlet's Spring application context AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext(); dispatcherContext.register(SpringDispatcherConfig.class); // Declare <servlet> and <servlet-mapping> for the DispatcherServlet ServletRegistration.Dynamic dispatcher = container.addServlet("ch03-servlet", new DispatcherServlet(dispatcherContext)); dispatcher.addMapping("*.html"); dispatcher.setLoadOnStartup(1); FilterRegistration.Dynamic corsFilter = container.addFilter("corsFilter", new CorsFilter()); corsFilter.setInitParameter("cors.allowed.methods", "GET, POST, HEAD, OPTIONS, PUT, DELETE"); corsFilter.addMappingForUrlPatterns(null, true, "/*"); FilterRegistration.Dynamic filter = container.addFilter("hiddenmethodfilter", new HiddenHttpMethodFilter()); filter.addMappingForServletNames(null, true, "/*"); FilterRegistration.Dynamic multipartFilter = container.addFilter("multipartFilter", new MultipartFilter()); multipartFilter.addMappingForUrlPatterns(null, true, "/*"); }
@Override protected Filter[] getServletFilters(){ // создание фильтра кодировки, который позволит работать с русскими символами CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter(); characterEncodingFilter.setEncoding("UTF-8"); characterEncodingFilter.setForceEncoding(true); // создание фильтра, который добавляет поддержку HTTP методов(например,таких как PUT) HiddenHttpMethodFilter httpMethodFilter = new HiddenHttpMethodFilter(); return new Filter[]{characterEncodingFilter, httpMethodFilter}; }
public void onServletContextStartup(ServletContext servletContext) throws ServletException { //encodingFilter registeredEncodingFilter(servletContext, CharacterEncodingFilter.class); //hiddenHttpMethodFilter registeredHiddenMethodFilter(servletContext, HiddenHttpMethodFilter.class); //multipartFilter registeredMultipartFilter(servletContext, SpringMultipartFilterProxy.class); //systemFilter registeredInitFilter(servletContext, BaseInitFilter.class); //ajaxAnywhere // registeredAjaxAnywhere(servletContext, AAFilter.class); }
@Override protected Filter[] getServletFilters() { CharacterEncodingFilter filter1 = new CharacterEncodingFilter(); filter1.setEncoding("utf-8"); filter1.setForceEncoding(true); HttpPutFormContentFilter filter2 = new HttpPutFormContentFilter(); HiddenHttpMethodFilter filter3 = new HiddenHttpMethodFilter(); LOG.info("Adding filter to dispatcher servlet[CharacterEncodingFilter,HttpPutFormContentFilter,HiddenHttpMethodFilter]"); return new Filter[]{filter1, filter2, filter3}; }
@Override protected Filter[] getServletFilters() { return new Filter[] { new HiddenHttpMethodFilter(), new DelegatingFilterProxy("a"), new DelegatingFilterProxy("b"), new DelegatingFilterProxy("c") }; }
@Test public void filterIsOrderedHighest() throws Exception { load(OrderedConfiguration.class); List<Filter> beans = new ArrayList<Filter>( this.context.getBeansOfType(Filter.class).values()); AnnotationAwareOrderComparator.sort(beans); assertThat(beans.get(0)).isInstanceOf(CharacterEncodingFilter.class); assertThat(beans.get(1)).isInstanceOf(HiddenHttpMethodFilter.class); }
/** * <p>默认关闭<p> * 加载HiddenHttpMethodFilter用于支持 HTTP PUT、DELETE(post模拟 put/delete) * 在这处理过程中 HttpServletRequest对象需要修改 故此过滤器放置位置需要靠前(放在过滤字符之后) * @param servletContext * @see HiddenHttpMethodFilter */ protected void initHiddenHttpMethodFilter(ServletContext servletContext){ String enableHiddenHttpMethod = servletContext.getInitParameter("enableHiddenHttpMethod"); if(BooleanUtils.valueOf(enableHiddenHttpMethod)){ //HiddenHttpMethodFilter HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter(); FilterRegistration filterRegistration = servletContext.addFilter("hiddenHttpMethodFilter", hiddenHttpMethodFilter); filterRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*"); } }
@Test public void filterIsOrderedHighest() throws Exception { load(OrderedConfiguration.class); List<Filter> beans = new ArrayList<Filter>( this.context.getBeansOfType(Filter.class).values()); AnnotationAwareOrderComparator.sort(beans); assertThat(beans.get(0), instanceOf(CharacterEncodingFilter.class)); assertThat(beans.get(1), instanceOf(HiddenHttpMethodFilter.class)); }
@Bean @ConditionalOnMissingBean(HiddenHttpMethodFilter.class) public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() { OrderedHiddenHttpMethodFilter filter = new OrderedHiddenHttpMethodFilter(); filter.setMethodParam("_disable_spring_mvc_hidden_method_for_fucking_zuul"); return filter; }
@Override protected Filter[] getServletFilters() { CharacterEncodingFilter charFilter = new CharacterEncodingFilter(); charFilter.setEncoding("UTF-8"); charFilter.setForceEncoding(true); return new Filter[] { new HiddenHttpMethodFilter(), charFilter, new HttpPutFormContentFilter() }; }
/** * Web Application. * * @param container * {@code ServletContext}. Representation of the context that is serving * the JEE application. Servlets, filters and listeners are registered * via this interface. */ private void initializeWebApplication(ServletContext container) { AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext(); dispatcherContext.register(WebConfig.class); DispatcherServlet webDispatcher = new DispatcherServlet(dispatcherContext); ServletRegistration.Dynamic servletReg = container.addServlet(dispatcherWebName, webDispatcher); servletReg.setLoadOnStartup(1); servletReg.addMapping(URL_PATTERN_WEB); HiddenHttpMethodFilter filter = new HiddenHttpMethodFilter(); FilterRegistration.Dynamic filterReg = container.addFilter("Hidden HTTP Method Filter", filter); filterReg.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST), true, dispatcherWebName); }
protected void createFilters(ServletContext ctx) { CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter(); characterEncodingFilter.setEncoding("UTF-8"); SimpleCORSFilter corsFilter = new SimpleCORSFilter(); corsFilter.setCorsAllowCredentials("true"); corsFilter.setCorsAllowMethods("GET, POST, PUT, PATCH, DELETE, OPTIONS"); corsFilter.setCorsAllowHeaders("content-type, x-requested-with, origin, accept, authorization, username, password, x-app-type, x-app-version, x-auth-token, soapaction"); corsFilter.setCorsExposeHeaders("content-type, cookie, x-requested-with, origin, accept, username, password, x-app-type, x-app-version, x-auth-token, soapaction"); corsFilter.setCorsMaxAge("3600"); ctx.addFilter("springSessionRepositoryFilter", DelegatingFilterProxy.class).addMappingForUrlPatterns( EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), false, FILTER_MAPPING); ctx.addFilter("simpleCORSFilter", DelegatingFilterProxy.class).addMappingForUrlPatterns( EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), false, FILTER_MAPPING); // ctx.addFilter("SimpleCorsFilter", corsFilter).addMappingForUrlPatterns( // EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), false, FILTER_MAPPING); ctx.addFilter("JsonHttpRequestFilter", new JsonHttpRequestFilter()).addMappingForUrlPatterns( EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), false, "/api/authenticate"); ctx.addFilter("springSecurityFilterChain", DelegatingFilterProxy.class).addMappingForUrlPatterns( EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), false, FILTER_MAPPING); ctx.addFilter("CharacterEncodingFilter", characterEncodingFilter).addMappingForUrlPatterns( EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), false, FILTER_MAPPING); ctx.addFilter("HiddenHttpMethodFilter", new HiddenHttpMethodFilter()).addMappingForUrlPatterns( EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), false, FILTER_MAPPING); ctx.addFilter("HttpPutFormContentFilter", new HttpPutFormContentFilter()).addMappingForUrlPatterns( EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), false, FILTER_MAPPING); ctx.addFilter("ShallowEtagHeaderFilter", new ShallowEtagHeaderFilter()).addMappingForUrlPatterns( EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), false, FILTER_MAPPING); }
@Override protected Filter[] getServletFilters() { HiddenHttpMethodFilter httpMethodFilter = new HiddenHttpMethodFilter(); CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter(); encodingFilter.setEncoding("UTF-8"); encodingFilter.setForceEncoding(true); return new Filter[] { httpMethodFilter, encodingFilter }; }
@Override public void onStartup(final ServletContext container) throws ServletException { // Create the root Spring application context final AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); rootContext.register(RootConfig.class); // Manage the lifecycle of the root application context final ContextLoaderListener contextLoaderListener = new ContextLoaderListener(rootContext); container.addListener(contextLoaderListener); // Create the dispatcher servlet's Spring application context final AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext(); dispatcherContext.register(DispatcherConfig.class); // Register and map the dispatcher servlet final Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext)); dispatcher.setLoadOnStartup(1); // Make the dispatcher the default servlet (using "/" as per the Servlet 3.0 specification) dispatcher.addMapping("/"); // Enables support for DELETE and PUT request methods with web browsers container.addFilter("hiddenHttpMethodFilter", HiddenHttpMethodFilter.class).addMappingForUrlPatterns(null, false, "/*"); // Add Spring Security support container.addFilter("springSecurityFilterChain", DelegatingFilterProxy.class).addMappingForUrlPatterns(null, false, "/*"); }
@Override protected Filter[] getServletFilters() { return new Filter[]{ new MDCInsertingServletFilter(), new HiddenHttpMethodFilter(), new OpenEntityManagerInViewFilter(), new RequestContextFilter(), new SecurityContextPersistenceFilter() }; }
@Override public void onStartup(ServletContext servletContext) throws ServletException { FilterRegistration.Dynamic method = servletContext.addFilter("hiddenMethod", new HiddenHttpMethodFilter()); method.addMappingForUrlPatterns(null, false, "/book/*", "/user/*"); }
@Override protected Filter[] getServletFilters() { return new Filter[]{new HiddenHttpMethodFilter(), new ResourceUrlEncodingFilter()}; }
@Bean @ConditionalOnMissingBean(HiddenHttpMethodFilter.class) public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() { return new OrderedHiddenHttpMethodFilter(); }
public static void main(String[] args) throws Exception { // can choose a custom port as the first main argument int port = DEFAULT_PORT; if (args.length > 0) { try { port = Integer.parseInt(args[0]); } catch (NumberFormatException e) { logger.warn("The first argument is not a port number: {}. Using default port: {}", args[0], DEFAULT_PORT); } } // Jetty customization for removing the server header final HttpConfiguration httpConfig = new HttpConfiguration(); httpConfig.setSendServerVersion(false); httpConfig.setSendDateHeader(true); final Server server = new Server(); final ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(httpConfig)); connector.setPort(port); server.setConnectors(new Connector[] {connector}); final ServletContextHandler sch = new ServletContextHandler(ServletContextHandler.NO_SESSIONS); // Spring dispatcher servlet final DispatcherServlet dispatcherServlet = new DispatcherServlet(); dispatcherServlet.setContextClass(AnnotationConfigWebApplicationContext.class); dispatcherServlet.setContextConfigLocation(Config.class.getName()); final ServletHolder sh = new ServletHolder(dispatcherServlet); sh.getRegistration().setMultipartConfig(new MultipartConfigElement("/var/tmp")); sch.addServlet(sh, "/"); // filter for allowing put and delete methods to be simulated via post sch.addFilter(HiddenHttpMethodFilter.class, "/*", EnumSet.noneOf(DispatcherType.class)); // filter that enforces UTF-8 encoding final CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter(); characterEncodingFilter.setEncoding("UTF-8"); characterEncodingFilter.setForceEncoding(true); sch.addFilter(new FilterHolder(characterEncodingFilter), "/*", EnumSet.noneOf(DispatcherType.class)); // get rid of the Jetty HTML error pages sch.setErrorHandler(new LoggingErrorHandler()); server.setHandler(sch); server.start(); server.join(); }
@Override protected Filter[] getServletFilters() { return new Filter[] { new HiddenHttpMethodFilter() }; }
@Override public void onStartup (final ServletContext servletContext) throws ServletException { // Create the root application context: final AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext (); rootContext.setServletContext (servletContext); rootContext.register (AdminConfig.class); rootContext.refresh (); // Manage the lifecycle of the root application context: servletContext.addListener (new ContextLoaderListener (rootContext)); servletContext.setInitParameter ("defaultHtmlEscape", "true"); servletContext.addListener (new CleanupListener ()); // Character encoding filter: force UTF-8 final CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter (); characterEncodingFilter.setEncoding ("UTF-8"); characterEncodingFilter.setForceEncoding (true); servletContext .addFilter ("characterEncodingFilter", characterEncodingFilter) .addMappingForUrlPatterns (EnumSet.of (DispatcherType.REQUEST), true, "/*"); // Spring HTTP method filter: provides overrides for HTTP method types using hidden form fields (e.g. PUT) servletContext .addFilter ("httpMethodFilter", new HiddenHttpMethodFilter ()) .addMappingForUrlPatterns (EnumSet.of (DispatcherType.REQUEST), true, "/*"); // Spring security filter: servletContext .addFilter ("springSecurityFilterChain", new DelegatingFilterProxy ()) .addMappingForUrlPatterns (EnumSet.of (DispatcherType.REQUEST), true, "/*"); // Configure the dispatcher servlet final AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext (); mvcContext.register (AdminWebMvcConfig.class); // Register the Spring MVC servlet: final ServletRegistration.Dynamic dispatcher = servletContext.addServlet ( "dispatcher", new DispatcherServlet (mvcContext) ); dispatcher.setLoadOnStartup (1); dispatcher.setAsyncSupported (true); // Attempt to map the servlet on "/": final Set<String> mappingConflicts = dispatcher.addMapping ("/"); if (!mappingConflicts.isEmpty ()) { for (final String conflict: mappingConflicts) { logger.error (String.format ("Mapping conflict: %s", conflict)); } throw new IllegalStateException ("Servlet cannot be mapped to '/' under Tomcat versions <= 7.0.14"); } }
@Bean public Filter hiddenHttpMethodFilter() { HiddenHttpMethodFilter filter = new HiddenHttpMethodFilter(); return filter; }
@Bean public FilterRegistrationBean hiddenFilterRegistrationBean() { return new FilterRegistrationBean(new HiddenHttpMethodFilter()); }