标签: spring-web

如何使用@RequestBody调用@RestController?

我有一个简单的servlet,如下所示:

@RestController
public class TestServlet {
    @RequestMapping(value = "/test1")
    public String test1() {
        return "test1";
    }

    @RequestMapping(value = "/test2")
    public String test2(@RequestBody TestClass req) {
        return "test2";
    }

    public static class TestClass {
        private String value;

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,只有不接收参数的servlet才起作用:

作品: http://localhost:8080/test1

不起作用: http://localhost:8080/test2?value=1234

org.springframework.http.converter.HttpMessageNotReadableException:缺少必需的请求正文:public java.lang.String

为什么@RequestBody注释不起作用?我错过了重要的一块吗?

java spring servlets spring-web

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

Spring启动更改服务器端口

我已经为Web应用程序创建了Spring Maven项目(使用archetype maven-archetype-webapp).我需要绑定不同于localhost和不同端口的ip.我在资源文件夹中创建了文件"application.properties"并添加了以下行:

server.port=8001
server.address= 192.168.1.91
Run Code Online (Sandbox Code Playgroud)

但是在启动时它仍使用端口默认值8080,而ip仍然是localhost.

我的WebInitializer类是:

package guard;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{RootConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{WebConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"*.html"};
    }

}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

java spring spring-mvc maven spring-web

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

如果授权标头不存在,则无法在 Webfilter 中发送自定义正文

我正在尝试使用 Webfilter 拦截 Spring Boot Webflux 应用程序(Spring boot 2.0.0.M7)中的所有请求,并检查“Authorization”标头是否存在。如果不存在,我想停止请求处理并发送自定义 HttpStatus 和自定义正文。自定义 HttpStatus 正在运行,但我无法将自定义消息写入 HTTP 正文。以下

import java.time.LocalDateTime;

import org.apache.commons.lang.SerializationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import reactor.util.context.Context;

public class RequestContextFilter implements WebFilter{

    Logger LOG = LoggerFactory.getLogger(RequestContextFilter.class);

    @Autowired
    private WebClient.Builder webclientBuilder;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        LOG.debug("Inside RequestContextFilter.."+ exchange);
        String authorizationHeader = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        if(authorizationHeader == null) {
            exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST); …
Run Code Online (Sandbox Code Playgroud)

spring spring-boot spring-web spring-webflux

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

是否可以在WebMvcTest中激活弹簧配置文件

给定一个类似的测试类:

@WebMvcTest
@RunWith(SpringRunner.class)
@SpringBootTest(properties = "spring.profiles.active=test")
public class MyControllerTest  {
... some tests
}
Run Code Online (Sandbox Code Playgroud)

我得到错误:

java.lang.IllegalStateException:配置错误:为测试类[com.example.MyControllerTest]找到了@BootstrapWith的多个声明:[@ org.springframework.test.context.BootstrapWith(value = class org.springframework.boot.test.autoconfigure .web.servlet.WebMvcTestContextBootstrapper),@ org.springframework.test.context.BootstrapWith(value = class org.springframework.boot.test.context.SpringBootTestContextBootstrapper)]

理想的目标是我只是在运行控制器测试,因此出于测试性能的原因,不想设置整个上下文-我只需要“ Web层”。

我可以删除该@SpringBootTest(properties = "spring.profiles.active=test")行-但是,现在我还没有激活测试配置文件,它可以通过属性以某种方式自定义Web上下文,例如将不再应用的杰克逊自定义。有没有一种方法可以只对“ Web层”进行测试并仍然激活弹簧轮廓?

我的环境是java version "10.0.2" 2018-07-17,spring boot1.5.16.RELEASE

spring-test spring-test-mvc spring-boot spring-web spring-boot-test

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

允许 Spring 在不同的 jars 中有多个 WebMvcConfigurer 实现

使用 Spring Web 时,在这种情况下,对于其余端点和使用 Spring Boot 2,我可以通过实现WebMvcConfigurer接口为我的应用程序配置拦截器:

@Configuration
public class SpringWebConfig implements WebMvcConfigurer
{
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor).addPathPatterns("/api/endpoint/**");
    }
}
Run Code Online (Sandbox Code Playgroud)

我通过执行以下操作以自动方式将此拦截器添加到我的大多数应用程序中:

  1. 创建一个“common-jar”,将上面的接口放在 package 下
    com.company.api
  2. 在每个应用程序中,将包添加com.company.api到 api 扫描。

这个 common 包还包含 Interceptor 和实用程序类来使这个拦截器工作,所以实际上,添加这个 common-jar 会自动将他的拦截器添加到应用程序中的所有操作中,这与 Spring 本身所做的概念类似:添加依赖项改变了 Spring 的默认配置。

我现在面临的问题是这种方法不能扩展到第二个 jar 中的第二个拦截器,因为我已经使用了 WebMvcConfigurer实现。我不能有两个。

我在考虑可能使用某种复合配置器模式,我们循环遍历每个配置器,收集所有拦截器,然后添加一次,但不幸的是 Spring 不允许这样做。我有哪些选择?

目前,我采用的方法是WebMvcConfigurer在每个需要它的应用程序中复制界面。当事情发生变化时,我感到很难过,我必须在每个应用程序中更改相同的代码片段。

java spring-mvc interceptor spring-boot spring-web

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

如何在 WebApplicationInitializer 中为 Servlet 过滤器指定 url-pattern?

我正在web.xml使用 Spring-web 的WebApplicationInitializer. 以下是定义的示例过滤器

<filter>
        <filter-name>sampleFilter</filter-name>
        <filter-class>com.SampleFilter</filter-class>
</filter>
<filter-mapping>
        <filter-name>sampleFilter</filter-name>
        <url-pattern>/sampleUrl</url-pattern>
</filter-mapping>
Run Code Online (Sandbox Code Playgroud)

现在 WebApplicationInitializer 类看起来像这样

class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
   @Override
  protected Filter[] getServletFilters() {
    return new Filter[]{new SampleFilter()};
  }
  //other methods
} 
Run Code Online (Sandbox Code Playgroud)

但正如您所看到的,过滤器应用于所有资源,而我只想将过滤器映射到/sampleUrl. 我们该怎么做呢?

java spring servlet-filters spring-web

0
推荐指数
1
解决办法
3430
查看次数

从变量中获取Spring动态HttpStatus

我有一个应用程序,我在其中使用以下命令从控制器返回动态HttpStatus代码: ResponseEntity

return new ResponseEntity<String>("Unrecognised request.", HttpStatus.BAD_REQUEST);
Run Code Online (Sandbox Code Playgroud)

下一个要求是将从数据库加载响应主体和状态代码。代码看起来像

String msg = <<loaded from database>>;
String status = <<loaded from database>>; //type can be changed to int
return new ResponseEntity<String>(msg, <..what to do here ??..>);
Run Code Online (Sandbox Code Playgroud)

不是状态代码将作为字符串/整数从数据库中检索。由于HttpStatus是一个枚举,所以我没有找到其他方法来做到这一点。

我的要求有解决方案吗?

java spring spring-web

0
推荐指数
1
解决办法
1654
查看次数

我对 org.springframework.mock.web 缺少什么依赖项?

MockMultipartFile我正在尝试在 Egads 的现有源代码中使用,但我不断收到此错误:package org.springframework.mock.web does not exist

这是更新后的 pom 文件:

  <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.yahoo.egads</groupId>
  <artifactId>egads</artifactId>

  <name>EGADS Anomaly Detection System</name>
  <description>EGADS system, consumes time series and outputs anomalies.</description>
  <version>0.4.0</version>

  <organization>
    <name>Yahoo Inc.</name>
    <url>https://www.yahoo.com/</url>
  </organization>
  <inceptionYear>2015</inceptionYear>

  <developers>
    <developer>
      <organization>Yahoo Inc.</organization>
      <organizationUrl>https://www.yahoo.com/</organizationUrl>
    </developer>
  </developers>

  <licenses>
    <license>
      <name>GPL V3</name>
      <url>https://www.gnu.org/licenses/gpl-3.0.en.html</url>
      <distribution>repo</distribution>
    </license>
  </licenses>

  <packaging>jar</packaging>

  <issueManagement>
    <system>Github</system>
    <url>https://github.com/yahoo/egads/issues</url>
  </issueManagement>

  <ciManagement>
    <system>Travis</system>
    <url>https://travis-ci.org/yahoo/egads</url>
  </ciManagement>

  <distributionManagement>
      <repository>
          <id>bintray-yahoo-egads</id>
          <name>yahoo-egads</name>
          <url>https://api.bintray.com/maven/yahoo/maven/egads;publish=1</url>
      </repository>
  </distributionManagement>
  <properties>
    <spring-boot.version>2.0.3.RELEASE</spring-boot.version>
  </properties>
  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
    </parent>

  <repositories>
    <repository> …
Run Code Online (Sandbox Code Playgroud)

java spring spring-web

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