【发布时间】:2015-06-06 19:53:47
【问题描述】:
我有一个由 jsps 和 servlet 组成的现有 Web 应用程序,我正在尝试将 SpringFramework Boot 添加到其中,以便我可以向应用程序添加一些新的简单休息服务。这些 rest 服务通过 jackson-databind 接受和返回 JSON。
这样做的问题是,读取上传文件的现有 servlet 的请求输入流现在在它被调用之前被消耗,因此文件不存在。
使用 maven,我在 pom.xml 中添加了以下内容...
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>1.2.1.RELEASE</version>
<scope>provided</scope>
</dependency>
...并且我添加了以下 RestApplication 类...
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class RestApplication extends SpringBootServletInitializer {
public static void main(final String[] args) {
SpringApplication.run(RestApplication.class, args);
}
@Override
protected final SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
return application.sources(RestApplication.class);
}
}
...和下面的控制器类...
@RestController
@RequestMapping(value = "/obj/mycontroller")
public class MyController
{
@RequestMapping(value = "/save", method = RequestMethod.POST)
public long save(final HttpServletRequest request,
final MyObject thing)
{
// save the thing
}
}
...一切正常,但是现在我的文件上传标准 servlet 已损坏。它仍然被调用,但它的输入流似乎是空的,因此找不到文件。这是该 servlet 的定义...
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@MultipartConfig
public class MediaUploadServlet
extends HttpServlet
{
protected void doPost(final HttpServletRequest request,
final HttpServletResponse response)
throws ServletException, IOException
{
if (ServletFileUpload.isMultipartContent(request)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> items = upload.parseRequest(request);
// do stuff with the files.
} catch (FileUploadException ex) {
// handle error
}
}
}
}
...现在项目是空的。
如果我去掉 @EnableAutoConfiguration 标记,那么 MediaUploadServlet 会再次工作,但 MyController 不能。所以我的问题是,如何将 Spring Boot 配置为 仅 在 MyController 上发挥作用或 不 在 MediaUploadServlet 上发挥作用?
【问题讨论】:
-
像这样注册您的辅助 servlet:stackoverflow.com/questions/20915528/…
-
是的,就是这样。谢谢!
-
如果您按照我的方式回答,我可以投票支持您的回答并删除我的回答。
-
已按要求回答...
标签: java servlets spring-boot