gpt4 book ai didi

java - SpringFramework Boot 在其他 servlet 读取输入流之前读取它

转载 作者:行者123 更新时间:2023-12-01 11:42:39 24 4
gpt4 key购买 nike

我有一个由 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);
}
}

...以及以下 Controller 类...

@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 上发挥作用?

最佳答案

您需要在 RestApplication 类中通过 bean 注册 servlet,如下所示

@Bean
public ServletRegistrationBean servletRegistrationBean(){
return new ServletRegistrationBean(new MediaUploadServlet(),"/mediaupload");
}

关于java - SpringFramework Boot 在其他 servlet 读取输入流之前读取它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29403141/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com