标签: spring-rest

Spring RestTemplate (setBufferRequestBody as false) 不喜欢包含 InputStream 对象的 MultiValueMap 请求体

我正在尝试以服务到服务的方式转发一个非常大的 csv 格式的文件。

因此,用户上传了一个非常大的 csv 文件(几个 GB),后端接收该文件作为 Spring 的MultipartFile抽象(我的版本是spring-web-4.3.3.RELEASE)。

之后,我MultipartFile使用RestTemplate. 一切工作正常,如果setBufferRequestBodytrue在要求的工厂,但如预期,它与内存不足的错误炸毁内存文件的字节被写入之前内部缓冲。但是,当我设置setBufferRequestBody为 时false,出现以下异常。

我发现 Spring 代理我的自定义请求工厂InterceptingClientHttpRequest,然后在内部将其委托给我的自定义请求工厂:

java.lang.UnsupportedOperationException: getBody not supported
    at org.springframework.http.client.HttpComponentsStreamingClientHttpRequest.getBodyInternal(HttpComponentsStreamingClientHttpRequest.java:84)
    at org.springframework.http.client.AbstractClientHttpRequest.getBody(AbstractClientHttpRequest.java:47)
    at org.springframework.http.client.InterceptingClientHttpRequest$InterceptingRequestExecution.execute(InterceptingClientHttpRequest.java:91)
    at org.springframework.cloud.netflix.metrics.MetricsClientHttpRequestInterceptor.intercept(MetricsClientHttpRequestInterceptor.java:65)
    at org.springframework.http.client.InterceptingClientHttpRequest$InterceptingRequestExecution.execute(InterceptingClientHttpRequest.java:85)
    at org.springframework.http.client.InterceptingClientHttpRequest.executeInternal(InterceptingClientHttpRequest.java:69)
    at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
    at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:619)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:595)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:516)
    at org.springframework.web.client.RestTemplate$$FastClassBySpringCGLIB$$aa4e9ed0.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
    at org.keycloak.adapters.springsecurity.client.KeycloakRestTemplate$$EnhancerBySpringCGLIB$$596ee8a2.exchange(<generated>)
    at us.deloitteinnovation.cfsa.service.dawb.impl.DatafileServiceImpl.doUploadInternal(DatafileServiceImpl.java:131)
    at us.deloitteinnovation.cfsa.service.dawb.impl.DatafileServiceImpl.uploadDataFile(DatafileServiceImpl.java:88)
    at …
Run Code Online (Sandbox Code Playgroud)

spring resttemplate spring-boot spring-rest

5
推荐指数
1
解决办法
3887
查看次数

如何在 spring Restapi 的 json 请求中的未知字段上抛出错误

我有一个 spring Rest api,它获取 json 数据并绑定到 pojo GetData。每当我收到未知字段时,它都不会失败或抛出任何异常。我的要求是当它接收到 json 数据中的未知字段时应该抛出错误。

public ResponseEntity<Error> saveLocation(@Valid @RequestBody GetData getdata,BindingResult bindingResults) {
Run Code Online (Sandbox Code Playgroud)

下面是我的 Pojo GetData

public class GetData{

@JsonProperty("deviceID")
@Pattern(regexp="^[\\p{Alnum}][-\\p{Alnum}\\p{L}]+[\\p{Alnum}]$",message = "Not a valid Device Id")
private String deviceID;


@JsonProperty("Coordinates")
@Pattern(regexp="^[\\p{Alnum}\\-][\\.\\,\\-\\_\\p{Alnum}\\p{L}\\s]+|",message = "Coordinates are not valid")
private String coordinates;}
Run Code Online (Sandbox Code Playgroud)

下面是我的 json 请求。

{
"deviceID" : "01dbd619-843b-4197-b954",
"Coordinates" : "12.984012,80.246712",
}
Run Code Online (Sandbox Code Playgroud)

现在,如果我发送带有额外字段的请求,例如国家/地区。它不会抛出任何错误。

{
    "deviceID" : "01dbd619-843b-4197-b954",
    "Coordinates" : "12.984012,80.246712",
    "country" : "dsasa"
}
Run Code Online (Sandbox Code Playgroud)

请建议我如何在 json 请求中发送未知属性时出现错误

spring spring-mvc jackson spring-boot spring-rest

5
推荐指数
1
解决办法
5306
查看次数

Spring Data mongodb聚合管道的分页结果

我在对聚合管道的结果进行分页时遇到了一些麻烦。在查看了In spring data mongodb 如何实现分页进行聚合后,我想出了一个感觉像 hacky 的解决方案。我首先执行匹配查询,然后按我搜索的字段分组,并对结果进行计数,将值映射到一个私有类:

private long getCount(String propertyName, String propertyValue) {
    MatchOperation matchOperation = match(
        Criteria.where(propertyName).is(propertyValue)
    );
    GroupOperation groupOperation = group(propertyName).count().as("count");
    Aggregation aggregation = newAggregation(matchOperation, groupOperation);
    return mongoTemplate.aggregate(aggregation, Athlete.class, NumberOfResults.class)
        .getMappedResults().get(0).getCount();
}

private class NumberOfResults {
    private int count;

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
}
Run Code Online (Sandbox Code Playgroud)

这样,我就能够为我返回的页面对象提供一个“总”值:

public Page<Athlete> findAllByName(String name, Pageable pageable) {
    long total = getCount("team.name", name);
    Aggregation aggregation = getAggregation("team.name", name, pageable); …
Run Code Online (Sandbox Code Playgroud)

spring-data-mongodb spring-boot spring-restcontroller spring-rest

5
推荐指数
1
解决办法
5560
查看次数

Spring Boot REST MVC 将具有不同字段名称的请求参数映射到对象

假设我想将一堆请求参数捕获为一个对象,如下所示:

@GetMapping("/")
public List<Item> filterItems(@Valid Filter filter){}
Run Code Online (Sandbox Code Playgroud)

Filter看起来像这样:

class Filter {
        public String status;
        public String start;
        public String end;
    }
Run Code Online (Sandbox Code Playgroud)

现在在 API 中请求参数名称state不再是status这样了?state=A&start=1&end=2。如何使这些请求参数映射到我的 Filter 对象而无需重命名status?我知道如果我有@RequestParam("state") String status它会起作用,但我希望它成为请求对象的一部分。

我尝试@JsonProperty('state')在字段中添加,但没有成功。

spring-mvc http-request-parameters spring-web spring-rest

5
推荐指数
0
解决办法
2862
查看次数

Spring-Boot 禁用响应头中的传输编码

问题陈述 - Spring-Boot(2.0.1.RELEASE 和嵌入式 Tomcat 服务器)中的一个简单的 RESTful 服务返回如下响应:

HTTP/1.1 200
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Tue, 01 May 2018 00:33:04 GMT

7d
{the-json-response-anticipated}
0
Run Code Online (Sandbox Code Playgroud)

经过一番查找,发现这是由于 header 引起的Transfer-Encoding: chunked。尝试设置以下内容application.properties

spring.http.encoding.force=false
spring.http.encoding.enabled=false
Run Code Online (Sandbox Code Playgroud)

但是,没有用。有什么方法可以禁用相同的功能吗?
我是否应该编写显式代码来形成参数设置为的标头false并将其设置为响应的标头?

tomcat http-headers spring-boot spring-rest

5
推荐指数
1
解决办法
2万
查看次数

使用 Angular 4 将 zip 文件上传到 spring Rest 控制器

我想从 Angular 4 将 .zip 文件上传到服务器(弹簧休息控制器)。请建议如何操作?

提前致谢

multipartform-data spring-rest angular

5
推荐指数
1
解决办法
7012
查看次数

获取纯文本形式的 XML

我有 Spring Rest API 的端点:

@PostMapping(value = "/v1/", consumes = { MediaType.APPLICATION_XML_VALUE,
            MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_XML_VALUE,
                    MediaType.APPLICATION_JSON_VALUE })
    public PaymentResponse handleMessage(@RequestBody PaymentTransaction transaction, HttpServletRequest request) throws Exception {

    // get here plain XML  

}
Run Code Online (Sandbox Code Playgroud)

XML 模型。

@XmlRootElement(name = "payment_transaction")
@XmlAccessorType(XmlAccessType.FIELD)
public class PaymentTransaction {
    public enum Response {
        failed_response, successful_response
    }

    @XmlElement(name = "transaction_type")
    public String transactionType;
    .........
}
Run Code Online (Sandbox Code Playgroud)

如何获取纯 XML 文本格式的 XML 请求?

我也尝试过使用 Spring 拦截器:我尝试了这段代码:

@SpringBootApplication
@EntityScan("org.plugin.entity")
public class Application extends SpringBootServletInitializer implements WebMvcConfigurer {

    @Override …
Run Code Online (Sandbox Code Playgroud)

java rest spring spring-restcontroller spring-rest

5
推荐指数
1
解决办法
1758
查看次数

如何在 Spring Boot 中使用 RESTful 和基本身份验证

你好,我使用 RESTful 进行基本身份验证,此代码是 RestController 的一部分:

@GetMapping("/jpa/users/{username}/goals")
public List<Goal> getAllGoals(@PathVariable String username) {
    userId = getUserIdFromUsername(username);
    return goalJpaRepository.findByUserId(userId); 
}

public Long getUserIdFromUsername(String username) {
    User user = userJpaRepository.findByUsername(username);
    userId = user.getId(); 
    return userId;
}
Run Code Online (Sandbox Code Playgroud)

我有一个问题,例如我正在使用 Postman 来检索特定用户的目标,如下所示:

http://localhost:8080/jpa/users/john/goals 带有 GET 请求

然后我对用户名 john 和该用户名的密码使用基本身份验证,然后我收到了 john 的目标。

之后,如果我对此链接http://localhost:8080/jpa/users/tom/goals执行 GET 请求,我会收到 Tom 的目标,但此时我已使用 john 登录,因此 john 可以看到他的目标,他也可以看到汤姆的目标。

问题是我如何访问 RestController 中的登录用户名,因为我想做这样的事情:

if (loginUsername == username) {
    return goalJpaRepository.findByUserId(userId);
} 

return "Access denied!";
Run Code Online (Sandbox Code Playgroud)

所以我想知道是否可以从HTTP Header访问登录用户名?

谢谢你!


更新- 是的,框架是 Spring Boot,我也使用 Spring Security …

java rest restful-authentication basic-authentication spring-rest

5
推荐指数
1
解决办法
7437
查看次数

使用 LDAP 身份验证的 Spring Boot REST API

所以我正在尝试构建一个将使用 LDAP 身份验证的 REST API。基本上,当我的登录端点被使用时,我希望它使用 httpBasic 身份验证检测凭据,然后针对我的 LDAP 服务器使用这些凭据。我还想考虑用户角色,保护端点,以便只有具有适当角色的某些用户才能访问所述端点。

是否有可能做到这一点?到目前为止,在我的阅读中,我还没有看到明确说明如何实现这一点的教程或文章。

*更新:我设法将其配置为能够使用 httpBasic 接受凭据。现在我想知道如何使用基于 LDAP 组的用户角色(例如经理、开发人员)为特定端点设置权限

java ldap spring-boot spring-rest

5
推荐指数
1
解决办法
8169
查看次数

具有多个数据库连接的 Spring Boot

我制作了一个简单的 SpringBoot REST 应用程序用于测试目的,其中表位于 2 个数据库中,一个是 Mysql,一个是 Postgresql。为了配置这 2 个连接,我使用了此处的说明,在第 6 点 -“Spring Boot 中的多个数据库”,一切似乎都很好,这 2 个连接已启动,但只有主连接有效。

因此,如果Mysql连接被注释为@Primay,则只有Mysql REST服务工作,在Postgresql上,所有表的错误都是“ org.hibernate.hql.internal.ast.QuerySyntaxException:<Entity_Name>未映射”。但是,如果我进行单个更改并在 Postgresql 连接上设置 @Primary,则所有 Postgres 表都可以正常工作,并且所有 Mysql 表都会给出相同的错误(表未映射)。

所以不知何故,我认为正确的连接不是根据包自动选择的。

更新:我在这里找到了另一个使用不同数据库类型的教程,我按照说明进行操作,但结果是相同的,辅助数据库中的所有表都给出错误“ org.hibernate.hql.internal.ast.QuerySyntaxException:<Entity_Name>不是映射”。我认为辅助连接未使用,不知何故主连接默认在错误的表上,但我不知道为什么。

我将这个小型 Github 项目与我的作品一起上传。 https://github.com/victorqedu/MultipleSpringBootDS

更新:在 DAO 类中,a 已经自动装配了构造函数,并且 @Autowire 设置了错误的 EntityManager(我认为这是问题的根源),我可以手动指定正确的 EntityManager 吗?

@Autowired
public AntibiogramaAntibioticeDAOHibernateImpl(EntityManager theEntityManager) {
    entityManager = theEntityManager;
}
Run Code Online (Sandbox Code Playgroud)

我还尝试了 EntityManager 上的注释 @PersistenceContext 但结果是相同的。

@PersistenceContext
private EntityManager entityManager;
Run Code Online (Sandbox Code Playgroud)

我不确定问题是 EntityManagaer 还是我从 EntityManager.unwrap 获得的会话,似乎关于此的文档很少......

spring-data-jpa spring-boot spring-rest

5
推荐指数
1
解决办法
1706
查看次数