我在jsp文件中有这个表单:
<form:form method="POST" commandName="advertForm" onsubmit="return checkAddress();" enctype="multipart/form-data">
<form:errors path="*" cssClass="errorblock" element="div"/>
<table>
<tr>
<td>Text:</td>
<td><form:input path="advert.text"/></td>
<td><form:errors path="advert.text" cssClass="error"/></td>
</tr>
<table id="fileTable">
<tr>
<td><input name="images[0]" type="file" /></td>
</tr>
<tr>
<td><input name="images[1]" type="file" /></td>
</tr>
</table>
<tr>
<td colspan="1"><a style="text-decoration: none" href="/"><input type="button" value="Cancel"/></a></td>
<td colspan="2"><input type="submit" value="Save"/></td>
</tr>
<input type="hidden"
name="${_csrf.parameterName}"
value="${_csrf.token}" />
</table>
</form:form>
和这个AdvertForm类:
public class AdvertForm {
private Advert advert;
private List<MultipartFile> images;
public Advert getAdvert() {
return advert;
}
public void setAdvert(Advert advert) {
this.advert = advert;
}
public List<MultipartFile> getImages() {
return images;
}
public void setImages(List<MultipartFile> images) {
this.images = images;
}
}
在相应的控制器中,我使用以下参数接收数据:
@ModelAttribute("advertForm") AdvertForm advertForm
问题是当sping-security.xml中的 csrf 被禁用时它工作正常 - 我可以在advertForm.getImages()中看到所选文件,但是当我启用csrf时它停止使用:< / p>
Invalid CSRF token found for http://localhost:8080
我尝试使用以下步骤解决此问题:
我在securityFilterChain:
之前添加了多部分过滤器<filter>
<filter-name>MultipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MultipartFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
我定义了filterMultipartResolver:
<bean id="filterMultipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="100000000" /></bean>
并将其添加到web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
......,
/WEB-INF/springWebMultipartContext.xml
</param-value>
</context-param>
在Tomcat 7中启用了CasualMultipartParsing(我使用独立库从IDE运行)
ctx.setAllowCasualMultipartParsing(真)
现在表单有效 - 我没有收到任何csrf错误。但是当控制器收到advertForm参数时,advertForm.getImages()返回null,但advertForm.getText()返回用户输入的文本。在日志中我可以看到这一行:
DEBUG CommonsMultipartResolver - Found multipart file [images[0]] of size 3117 bytes with original filename [11111111.txt], stored in memory
我的错误在哪里?
答案 0 :(得分:2)
我忘了提到我定义了这个bean:
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
这是一个问题。删除这个bean之后一切正常。