我正在运行带有嵌入式 tomcat 容器的 spring-boot 服务。
有没有办法通过通用应用程序属性或 EmbeddedServletContainerFactory来限制 HTTP PUT请求的大小?谢谢
我的一个控制器中的构造函数有一些问题。我尝试在构造函数中调用一项服务。该服务在 AbstractController 中自动装配,但我得到了一个空指针异常。
一个组件:
@Component
@RestController
@RequestMapping(value = "/test", ...)
public class AController extends AbstractController {
@Autowired
SomeService someService;
public AController(){
globalService.setClazz(Test.class);
}
....
Run Code Online (Sandbox Code Playgroud)
这里是抽象控制器:
public abstract class AbstractController<T> {
@Autowired
GlobalService globalService;
...
Run Code Online (Sandbox Code Playgroud)
这里例外。它被扔进去globalService.setClazz(Test.class);
Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.x.server.controller.AController]: Constructor threw exception; nested exception is java.lang.NullPointerException -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.3.1.RELEASE:run (default-cli) on project eza: An exception occurred while running. null
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:216)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145) …Run Code Online (Sandbox Code Playgroud) 我正在使用弹簧。我想实现休息控制器将文件上传到服务器。我发现了很多这样的例子:
public ResponseEntity doSomething(@PathVariable String paramOne, @RequestParam(required = false, name="file") List<MultipartFile> attachments
) throws IOException {
//Some logic here
}
Run Code Online (Sandbox Code Playgroud)
然后我用邮递员测试它,我创建了一个“表单数据”类型的请求,添加婴儿车名称“文件”,选择类型文件,然后选择文件。它工作正常。
它创建一个 post 请求作为多部分请求。但出于某些原因,我不想使用多部分发布请求。所以我想通过在邮递员类型“二进制”中选择来上传文件。所以我的问题:
spring 能否以某种方式映射这种请求,以便我在处理程序方法中将输入文件作为参数?(我知道我可以获取 HttpServletRequest 并从中获取 InputStream,但是有更好的方法吗?)
通过这种方法,我只能得到输入流。传递文件名的好方法是什么?
这种方法的主要缺点是什么?
我无法直接获取JSONObject,此代码有效:
RestTemplate restTemplate = new RestTemplate();
String str = restTemplate.getForObject("http://127.0.0.1:8888/books", String.class);
JSONObject bookList = new JSONObject(str);
Run Code Online (Sandbox Code Playgroud)
但是这段代码没有:
JSONObject bookList = restTemplate.getForObject("http://127.0.0.1:8888/books", JSONObject.class);
Run Code Online (Sandbox Code Playgroud)
可能是什么问题呢?它没有给出错误,但最后我有一个空的JSONObject.
我的pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>library-client</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>LibraryClient</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
</dependency>
</dependencies>
<build> …Run Code Online (Sandbox Code Playgroud) 我的用例:
tmp文件(我实际上不需要创建真实文件,但我需要有java.io.File实例)tmp永久删除文件我的代码如下所示:
@GetMapping(produces = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<MultiValueMap<String, Object>> regeneratePdfTest() throws IOException {
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
File tempFile = File.createTempFile("temp-file-name", ".tmp");
processFile(tempFile);
parts.add("file", new HttpEntity<>(new FileSystemResource(tempFile)));
parts.add("meta-data", new HttpEntity<>(someObject));
return new ResponseEntity<>(parts, HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)
(这段代码最适合这种情况吗?)
我知道File.deleteOnExit(),但文档说
根据 Java 语言规范的定义,仅在虚拟机正常终止时才会尝试删除
就我而言,我想在响应后立即删除文件(文件有一些私人信息,我不想保留它们,也是安全内存,因为我不再需要这个文件)。
文件大小可能非常大(超过 200MB)。
更新 1: 如果发生错误我也想删除文件。
我有一个数据类,如下所示:
public class Person {
private String name;
private Long code;
// corresponding getters and setters
}
Run Code Online (Sandbox Code Playgroud)
我想编写两个Web服务,提供两个不同的JSON表示形式的Person.例如,其中一个提供{"name":"foo"}但另一个提供{"name":"foo", "code":"123"}.
作为一个更复杂的场景,假设Person有一个引用属性,例如address.地址也有自己的属性,我希望我的两个Web服务都考虑这个属性,但每个属性都以自己的方式执行.
我的SpringMVC视图应该如何?
请注意,我是SpringMVC的新手.请在答案旁边给我一个示例代码.
更新1:几天后,所有答案都促使我解决控制器中的问题或通过注释数据类.但我希望在视图中执行此操作,而不再使用java代码.我可以在JSP文件或百万美元模板甚至.properties文件中执行此操作吗?
更新2:我找到了json-taglib.但不知何故,它被排除在新的升级之外.有没有类似的解决方案?
假设我们有以下类:
public abstract class Investment {
private String investmentType;
// getters & setters
}
public class Equity extends Investment {
}
public class Bond extends Investment {
}
public class InvestmentFactory {
public static Investment getTypeFromString(String investmentType) {
Investment investment = null;
if ("Bond".equals(investmentType)) {
investment = new Bond();
} else if ("Equity".equals(investmentType)) {
investment = new Equity();
} else {
// throw exception
}
return investment;
}
}
Run Code Online (Sandbox Code Playgroud)
以下内容@RestController:
@RestController
public class InvestmentsRestController {
private InvestmentRepository investmentRepository; …Run Code Online (Sandbox Code Playgroud) 我按照 spring.io Pivotal 教程获得了带有 MySQL 数据库的 REST API,并且事情进展顺利。但是,我发现了一种我无法配置或解决的行为。
当我使用内置功能从 PagingAndSortingRepository 检索我的资源时,生成的 REST 会自动分页并使用有用的 HAL 链接(_links、self、search、链接的资源等)进行封装。我想用那个。
当我实现我的控制器来自定义 PostMapping 行为并引入健全性检查、验证等时,GetMapping 停止工作。所以我重新实现了一个利用我的服务层的 GetMapping。
不幸的是,这样做破坏了之前提供的 HATEOAS。
我想要的是能够自定义 PostMapping,但完全像默认值一样保留 GetMapping。如果可能的话,我很想避免自己编写它,因为我知道框架可以提供它。
有没有办法做到这一点?
控制器:
@RestController
public class PartyMemberController {
@Autowired
PartyMemberService partyMemberService;
@RequestMapping(method = RequestMethod.GET, value = "/partyMembers")
public ResponseEntity<Iterable<PartyMember>> getAllPartyMembers() {
Iterable<PartyMember> partyMemberList = partyMemberService.getAll();
return new ResponseEntity<>(partyMemberList, HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.POST, value = "/partyMembers")
public ResponseEntity<PartyMember> addEmployee(@Valid @RequestBody PartyMember partyMember) {
if (partyMemberService.exists(partyMember)) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
partyMember = …Run Code Online (Sandbox Code Playgroud) I'm creating simple controller server for spring reactive project. While setting redirection to another location, I have found an error when calling http://localhost:8080/:
There was an unexpected error (type=Internal Server Error, status=500).
ModelAttributeMethodArgumentResolver does not support multi-value reactive type wrapper: interface reactor.netty.http.server.HttpServerResponse
java.lang.IllegalStateException: ModelAttributeMethodArgumentResolver does not support multi-value reactive type wrapper: interface reactor.netty.http.server.HttpServerResponse
at org.springframework.util.Assert.state(Assert.java:94)
at org.springframework.web.reactive.result.method.annotation.ModelAttributeMethodArgumentResolver.resolveArgument(ModelAttributeMethodArgumentResolver.java:112)
at org.springframework.web.reactive.result.method.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:123)
at org.springframework.web.reactive.result.method.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:190)
at org.springframework.web.reactive.result.method.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:133)
at org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerAdapter.lambda$handle$1(RequestMappingHandlerAdapter.java:200)
at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:44)
...
Run Code Online (Sandbox Code Playgroud)
This is the controller code:
There was an unexpected error (type=Internal …Run Code Online (Sandbox Code Playgroud) java reactive-programming spring-restcontroller spring-webflux
我在这上面花了一天时间,但找不到有效的解决方案。在我们的应用程序中,我们有几个端点可以返回大响应。我一直在尝试寻找一种机制,允许我们在处理数据库查询结果时流式传输响应。主要目标是限制服务端的峰值内存使用(不需要内存中的整个响应)并最小化响应第一个字节的时间(如果响应没有开始进入,客户端系统会超时)指定时间 - 10 分钟)。我真的很惊讶这这么难。
我找到了 StreamingResponseBody ,它看起来很接近我们想要的东西,虽然我们并不真正需要异步方面,但我们只希望能够在处理查询结果时开始流式传输响应。我也尝试过其他方法,例如使用@ResponseBody 进行注释、返回 void 并添加 OutputStream 的参数,但这不起作用,因为传递的 OutputStream 基本上只是一个缓存整个结果的 CachingOutputStream。这是我现在所拥有的......
资源方法:
@GetMapping(value = "/catalog/features")
public StreamingResponseBody findFeatures(
@RequestParam("provider-name") String providerName,
@RequestParam(name = "category", required = false) String category,
@RequestParam("date") String date,
@RequestParam(value = "version-state", defaultValue = "*") String versionState) {
CatalogVersionState catalogVersionState = getCatalogVersionState(versionState);
log.info("GET - Starting DB query...");
final List<Feature> features
= featureService.findFeatures(providerName,
category,
ZonedDateTime.parse(date),
catalogVersionState);
log.info("GET - Query done!");
return new StreamingResponseBody() {
@Override
public void writeTo(OutputStream outputStream) throws IOException {
log.info("GET - …Run Code Online (Sandbox Code Playgroud) java ×8
spring ×4
spring-mvc ×4
spring-boot ×3
spring-rest ×2
http-chunked ×1
json ×1
rest ×1
resttemplate ×1
tomcat ×1