标签: spring-rest

如何在不同的端口上运行@RestController?

我正在用来spring-rest创建一些@RestControllerservlet。该应用程序不是在网络服务器上运行,而是作为带有嵌入式 tomcat 的简单命令行工具运行。

它们中的大多数应该在公共端口上运行,该端口是使用server.port=80属性指定的。

问题:如何@RestController在不同端口上运行不同的程序?那么其中一些只能在内部访问吗?

@RestController 
@RequestMapping("test")
public class TestServlet {

    @RequestMapping(value = "/", method = RequestMethod.GET, produces = MediaType.TEXT_PLAIN_VALUE)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public String test() { return "OK"; }
}
Run Code Online (Sandbox Code Playgroud)

java rest spring spring-rest

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

Spring REST 上传文件为二进制文件

我正在使用弹簧。我想实现休息控制器将文件上传到服务器。我发现了很多这样的例子:

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 请求作为多部分请求。但出于某些原因,我不想使用多部分发布请求。所以我想通过在邮递员类型“二进制”中选择来上传文件。所以我的问题:

  1. spring 能否以某种方式映射这种请求,以便我在处理程序方法中将输入文件作为参数?(我知道我可以获取 HttpServletRequest 并从中获取 InputStream,但是有更好的方法吗?)

  2. 通过这种方法,我只能得到输入流。传递文件名的好方法是什么?

  3. 这种方法的主要缺点是什么?

java rest spring spring-restcontroller spring-rest

6
推荐指数
0
解决办法
1009
查看次数

什么属于控制器层,什么属于服务层?

我有一个简单的 Spring-Boot Restful 应用程序。我有一个控制器层和一个存储库层,但没有服务层。让我向您展示我的 Controller 方法之一:

@RequestMapping(value = "users/{id}", method = RequestMethod.GET)
public Resource<UserResource> get(@PathVariable Long id) throws NotFoundException {
    log.info("Invoked method: get with ID: " + id);
    log.warn("Searching for user with ID " + id);
    User user = userRepository.findOne(id);
    if (user == null){
        log.error("Unexpected error, User with ID " + id + " not found");
        throw new NotFoundException("User with ID " + id + " not found");
    }
    log.info("User found. Sending request back. ID of user is " + …
Run Code Online (Sandbox Code Playgroud)

java rest spring spring-boot spring-rest

6
推荐指数
2
解决办法
4550
查看次数

spring jpa - 必须至少有一个JPA元模型*

有谁知道为什么它不起作用?

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
06/04/2017 14:11:24.732 ERROR [main] - org.springframework.boot.SpringApplication: Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:742)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) …
Run Code Online (Sandbox Code Playgroud)

java sql-server spring-data-jpa spring-boot spring-rest

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

使用 Spring Rest Template 时,比较方法违反了其一般契约

我们的一个应用程序正在通过 Spring Rest 模板调用另一个应用程序。

HttpEntity<Object> httpEntity = new HttpEntity<>(null);
restTemplate.exchange(URL, HttpMethod.GET, httpEntity,String.class)
Run Code Online (Sandbox Code Playgroud)

我们尚未为请求显式设置任何标头。我们遇到以下异常:

Caused by: java.lang.IllegalArgumentException: Comparison method violates its general contract!
    at java.util.TimSort.mergeHi(TimSort.java:895)
    at java.util.TimSort.mergeAt(TimSort.java:512)
    at java.util.TimSort.mergeCollapse(TimSort.java:437)
    at java.util.TimSort.sort(TimSort.java:241)
    at java.util.Arrays.sort(Arrays.java:1512)
    at java.util.ArrayList.sort(ArrayList.java:1454)
    at java.util.Collections.sort(Collections.java:175)
    at org.springframework.http.MediaType.sortBySpecificity(MediaType.java:441)
    at org.springframework.web.client.RestTemplate$AcceptHeaderRequestCallback.doWithRequest(RestTemplate.java:691)
    at org.springframework.web.client.RestTemplate$HttpEntityRequestCallback.doWithRequest(RestTemplate.java:743)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:567)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:530)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:448)
Run Code Online (Sandbox Code Playgroud)

我们使用的Java版本是:1.8.0_45和Spring:4.1.6

如果有人能提供帮助那就太好了。如果需要,我很乐意提供更多详细信息。

期待中感谢。

java spring spring-mvc spring-rest

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

Spring Boot中处理异常的正确方法

我正在阅读 Spring 文档,发现从创建子类ResponseEntityExceptionHandler是处理异常的好方法。但是,我尝试以不同的方式处理异常,因为我需要BusinessExceptionsTechnicalExceptions.

创建了一个BusinessFault封装异常详细信息的 bean :

业务故障.java

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonInclude(value = Include.NON_NULL)
public class BusinessFault {

    @JsonProperty(value = "category")
    private final String CATEGORY = "Business Failure";
    protected String type;
    protected String code;
    protected String reason;
    protected String description;
    protected String instruction;

    public BusinessFault(String type, String code, String reason) {
        this.type = type;
        this.code = code;
        this.reason = reason;
    }

    public BusinessFault(String type, String code, String reason, String description, …
Run Code Online (Sandbox Code Playgroud)

java spring spring-boot spring-restcontroller spring-rest

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

如何在 spring-web servlet 中接受 text/csv 作为内容类型?

我想创建一个生成text/csv内容的简单网络服务。但我不能要求它:

@RestController
public class MyServlet {
    @PostMapping(produces = {"text/csv", "application/json"})
    public Object post() {
        //...
    }
}

spring.mvc.contentnegotiation.media-types.csv=text/csv
Run Code Online (Sandbox Code Playgroud)

当我发送带有 http 标头的 post 请求时Content-Type: text/csv,出现以下错误:

415:Content type 'text/csv' not supported

这是我的配置:

@Configuration
public class ContentNegotiationConfiguration implements WebMvcConfigurer {
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer
                .favorParameter(true) //favor &format=csv
                .defaultContentType(MediaType.APPLICATION_JSON)
                .parameterName(format);
                //.mediaType("csv", new MediaType("text", "csv")) //also tried without success
    }
}
Run Code Online (Sandbox Code Playgroud)

java spring spring-web spring-rest

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

春天无法返回带有异常详细信息的ResponseEntity

我创建了一个Spring Restful Service和Spring MVC应用程序。

Restful Service :: Restful Service返回一个实体(如果它存在于数据库中)。如果不存在,则在ResponseEntity对象中返回自定义Exception信息。

它正在使用邮递员进行预期的测试。

@GetMapping(value = "/validate/{itemId}", produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
public ResponseEntity<MyItem> validateItem(@PathVariable Long itemId, @RequestHeader HttpHeaders httpHeaders) {

    MyItem myItem = myitemService.validateMyItem(itemId);
    ResponseEntity<MyItem> responseEntity = null;
    if (myItem == null) {
        throw new ItemNotFoundException("Item Not Found!!!!");
    }
    responseEntity = new ResponseEntity<MyItem>(myItem, headers, HttpStatus.OK);
    return responseEntity;
}
Run Code Online (Sandbox Code Playgroud)

如果所请求的实体不存在,Restful Service将在下面返回。

@ExceptionHandler(ItemNotFoundException.class)
public ResponseEntity<ExceptionResponse> itemNotFEx(WebRequest webRequest, Exception exception) {
    System.out.println("In CREEH::ItemNFE");
    ExceptionResponse exceptionResponse = new ExceptionResponse("Item Not Found Ex!!!", new Date(), webRequest.getDescription(false));
    ResponseEntity<ExceptionResponse> …
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc spring-boot spring-rest

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

spring boot 2中如何处理@Requestbody中对象抛出的异常

我有一个休息控制器类,如下所示,当用户对象无效时,它会抛出自定义异常。但是这些异常被 spring 框架包装,而不是由控制器建议中定义的特定异常处理程序处理。

@PostMapping
public ResponseEntity<String> process(
  @PathVariable(User_id) String id,
  @Valid @RequestBody(required = false) User user) {
 }
Run Code Online (Sandbox Code Playgroud)

例如,Json 映射异常被包装为 org.springframework.http.converter.HttpMessageNotReadableException,并且不会通过控制器建议中的以下异常处理程序进行处理。

@ExceptionHandler(JsonMappingException.class)
public ResponseEntity<ErrorMessage> handleJsonMappingException(JsonMappingException e){
//process to return error message
}
Run Code Online (Sandbox Code Playgroud)

如何处理构建请求主体对象时抛出的这些特定异常?

实际收到的异常:

2018-09-16 23:14:07,671 ERROR [qtp1824013753-23] c.m.a.c.e.m.MyExceptionHandler [MyExceptionHandler.java:111] Unhandled exception : Type definition error: [simple type, class com.common.model.User]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.common.model.User`, problem: '123ghijk' is not a valid DeptName
 at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: com.common.model.Employee["DeptName"])
org.springframework.http.converter.HttpMessageConversionException: Type definition …
Run Code Online (Sandbox Code Playgroud)

exception spring-mvc spring-boot spring-restcontroller spring-rest

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

从 MultiValueMap 获取值

我使用以下代码从 HTTP 请求获取值:

@PostMapping(consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, value = "/v1/notification")
  public ResponseEntity<String> handleNotifications(@RequestBody MultiValueMap<String, Object> keyValuePairs) {

    LOGGER.debug("handleFormMessage");
    LOGGER.debug("keyValuePairs: {}", keyValuePairs);

    String unique_id = String.valueOf(keyValuePairs.get("unique_id"));

    System.out.println("!!!!!!!!!!!!!! ! unique_id " + unique_id);
}
Run Code Online (Sandbox Code Playgroud)

但我得到这个值:!!!!!!!!!!!!!! ! unique_id [24q376c3ts2kh3o3220rry322dfe2k7y]

[]有没有办法在没有经典的情况下从字符串中删除String result = str.substring(0, index) + str.substring(index+1);

有没有办法获取值?

我用它来发布值:

在此输入图像描述

java spring-boot spring-restcontroller spring-rest

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