001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.wicket.protocol.http; 018 019import java.util.Map; 020 021import org.apache.wicket.Component; 022import org.apache.wicket.ajax.AjaxRequestTarget; 023import org.apache.wicket.markup.html.form.Form; 024import org.apache.wicket.markup.html.form.FormComponent; 025import org.apache.wicket.util.visit.IVisitor; 026 027/** 028 * This listener updates the {@link Form}'s <em>enctype</em> whenever a multipart {@link FormComponent} 029 * is added to the {@code AjaxRequestTarget}. 030 * This is needed because the multipart form component may change its visibility/enablement and thus 031 * change the multipart-ness of the whole form. 032 */ 033public class MultipartFormComponentListener implements AjaxRequestTarget.IListener 034{ 035 static final String ENCTYPE_URL_ENCODED = "application/x-www-form-urlencoded"; 036 037 @Override 038 public void onAfterRespond(final Map<String, Component> map, final AjaxRequestTarget target) 039 { 040 target.getPage().visitChildren(Form.class, (IVisitor<Form<?>, Void>) (form, formVisitor) -> { 041 if (form.isVisibleInHierarchy()) { 042 form.visitFormComponents((formComponent, visit) -> { 043 if (formComponent.isMultiPart()) { 044 String enctype = form.isMultiPart() ? Form.ENCTYPE_MULTIPART_FORM_DATA : ENCTYPE_URL_ENCODED; 045 target.appendJavaScript(String.format("Wicket.$('%s').enctype='%s'", form.getMarkupId(), enctype)); 046 visit.stop(); 047 } 048 }); 049 } else { 050 formVisitor.dontGoDeeper(); 051 } 052 }); 053 } 054}