标签: spring-restcontroller

上传文件springboot必需的请求部分'文件'不存在

我想在我的spring启动应用程序中添加一个上传功能; 这是我的上传Rest Controller

package org.sid.web;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.sid.entities.FileInfo;

@RestController
public class UploadController {
  @Autowired
  ServletContext context;

  @RequestMapping(value = "/fileupload/file", …
Run Code Online (Sandbox Code Playgroud)

upload spring-boot postman spring-restcontroller

18
推荐指数
4
解决办法
4万
查看次数

弹簧静止控制器返回特定字段

我一直在思考使用Spring MVC设计JSON API的最佳方法.我们都知道IO很昂贵,因此我不想让客户端进行多次API调用以获得他们需要的东西.但与此同时,我不一定要回厨房水槽.

作为一个例子,我正在开发类似于IMDB的游戏API,而不是用于视频游戏.

如果我返回与游戏相关的所有内容,它将看起来像这样.

/ API /游戏/ 1

{
    "id": 1,
    "title": "Call of Duty Advanced Warfare",
    "release_date": "2014-11-24",
    "publishers": [
        {
            "id": 1,
            "name": "Activision"
        }
    ],
    "developers": [
        {
            "id": 1,
            "name": "Sledge Hammer"
        }
    ],
    "platforms": [
        {
            "id": 1,
            "name": "Xbox One",
            "manufactorer": "Microsoft",
            "release_date": "2013-11-11"
        },
        {
            "id": 2,
            "name": "Playstation 4",
            "manufactorer": "Sony",
            "release_date": "2013-11-18"
        },
        {
            "id": 3,
            "name": "Xbox 360",
            "manufactorer": "Microsoft",
            "release_date": "2005-11-12"
        }
    ],
    "esrbRating": {
        "id": 1,
        "code": …
Run Code Online (Sandbox Code Playgroud)

java rest spring spring-mvc spring-restcontroller

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

@RestController和@RepositoryRestController之间的区别

什么是典型的用例代码,显示这两个注释之间的区别 - 意味着@RestController@RepositoryRestController- ?

spring-mvc spring-data spring-data-rest spring-restcontroller

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

如何为Spring RESTful Web服务创建Spring Interceptor

我有一些没有web.xml的Spring RESTful(RestControllers)Web服务,我使用Spring启动来启动服务.

我想为Web服务添加授权层,并希望在实际调用Web服务本身之前将所有http请求路由到一个前端控制器.(我有一个代码来模拟autherisation层的会话行为,根据我从客户端发送的每个httpRequest生成的密钥来验证用户).

是否有任何标准Spring解决方案将所有请求路由到过滤器/前端控制器?

提前谢谢,Praneeth

编辑:添加我的代码

控制器:`

@RestController
public class UserService {
    UserDAO userDAO = new UserDAO();

    @RequestMapping(value="/login", method = RequestMethod.POST)
    @LoginRequired
    public String login(@RequestParam(value="user_name") String userName, @RequestParam(value="password") String password, HttpServletRequest request){
        return userDAO.login(userName, password);
    }
}`
Run Code Online (Sandbox Code Playgroud)

拦截器:

`

public class AuthenticationInterceptor implements HandlerInterceptor  {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
        System.out.println("In Interceptor");
        //return super.preHandle(request, response, handler);
        return true;
    }
    @Override
    public void postHandle( HttpServletRequest request, HttpServletResponse response,
            Object handler, ModelAndView modelAndView) throws Exception …
Run Code Online (Sandbox Code Playgroud)

spring-mvc spring-restcontroller spring-rest

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

失去了一天的约会

在客户端,我使用dd/MM/yyyy日期格式.该字段使用twitter bootstrap 3日期时间选择器(https://eonasdan.github.io/bootstrap-datetimepicker/)

我通过twitter bootstrap 3日期时间选择器24/07/2015
进入我发送的json,我看到:生日:"24/07/2015"

在我的dto,我做

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy")
private Date birthdate;
Run Code Online (Sandbox Code Playgroud)

当我在服务器上收到日期时,在我的dto中看到:23/07/2015 19:00

有一天失去了.

任何解释?

java json jackson orika spring-restcontroller

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

org.apache.catalina.connector.ClientAbortException:java.io.IOException:APR错误:-32

在我的Spring Boot + Tomcat 8项目中,我配置了@ControllerAdvice如下所示:

@ControllerAdvice
public class GlobalControllerExceptionHandler {

    final static Logger logger = LoggerFactory.getLogger(GlobalControllerExceptionHandler.class);

    private static final String ERROR = "error";

    @ExceptionHandler
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map<String, ResponseError> handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.debug("API error", e);
        return createResponseError(HttpStatus.BAD_REQUEST.value(), e.getMessage());
    }

    protected Map<String, ResponseError> createResponseError(int httpStatus, String message) {
        Map<String, ResponseError> responseError = new HashMap<String, ResponseError>();
        responseError.put(ERROR, new ResponseError(httpStatus, message));
        return responseError;
    }

}
Run Code Online (Sandbox Code Playgroud)

一切正常,除了客户端发送复杂且不正确的JSON文档并且我的服务器逻辑因以下异常而失败的情况:

2836538 WARN  o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Failed to invoke @ExceptionHandler method: …
Run Code Online (Sandbox Code Playgroud)

tomcat jackson tomcat8 spring-boot spring-restcontroller

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

如何使用Spring Boot的'spring.jackson.date-format'属性?

根据Current SpringBoot参考指南,如果我设置spring.jackson.date-format属性,它将:Date format string or a fully-qualified date format class name. For instance 'yyyy-MM-dd HH:mm:ss'.

但是,Spring Boot 1.5.3无法以这种方式工作.

为了演示,从这个类开始:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Instant;

@SpringBootApplication
public class DemoApplication {
  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
}

@RestController
class NowController{

  @GetMapping("/now")
  Instant getNow(){
    return Instant.now();
  }

}
Run Code Online (Sandbox Code Playgroud)

还有这个 src/main/resources/application.properties

spring.jackson.date-format=dd.MM.yyyy
Run Code Online (Sandbox Code Playgroud)

这个build.gradle:

buildscript {
    ext {
        springBootVersion = '1.5.3.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies { …
Run Code Online (Sandbox Code Playgroud)

spring jackson spring-boot spring-restcontroller spring-rest

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

Spring Boot 无法自动装配 @ConfigurationProperties

这是我的FileStorageProperties课:

 @Data
 @ConfigurationProperties(prefix = "file")
 public class FileStorageProperties {
       private String uploadDir;
 }
Run Code Online (Sandbox Code Playgroud)

这让我说:未通过 @enableconfigurationproperties 注册或标记为 spring 组件

这是我的FileStorageService

@Service
public class FileStorageService {

private final Path fileStorageLocation;

@Autowired
public FileStorageService(FileStorageProperties fileStorageProperties) {
    this.fileStorageLocation = Paths.get(fileStorageProperties.getUploadDir())
            .toAbsolutePath().normalize();

    try {
        Files.createDirectories(this.fileStorageLocation);
    } catch (Exception ex) {
        throw new FileStorageException("Could not create the directory where the uploaded files will be stored.", ex);
    }
}

public String storeFile(MultipartFile file) {
    // Normalize file name
    String fileName = …
Run Code Online (Sandbox Code Playgroud)

java spring bean-validation spring-boot spring-restcontroller

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

Spring Boot RestController,关于错误状态响应体,错误消息为空

在我的 Spring Boot RestController 上,我想通过抛出自定义异常将自定义错误消息传递给响应正文。我正在关注https://dzone.com/articles/spring-rest-service-exception-handling-1上的指南

这些是我的代码片段:

用户未找到异常

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;


@ResponseStatus(HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {
    public UserNotFoundException(String message) {
        super(message);
    }
}
Run Code Online (Sandbox Code Playgroud)

简化的 RestController

@RestController
public class CreateRfqController {

    @PostMapping("api/create-rfq")
    public ResponseEntity<Rfq> newRfq(@RequestBody Rfq newRfq) {
        throw new UserNotFoundException("User Not Found");
    }
}

Run Code Online (Sandbox Code Playgroud)

调用我的 Rest API 时,我总是收到一条空消息:

{
    "timestamp": "2020-06-24T18:23:30.846+00:00",
    "status": 404,
    "error": "Not Found",
    "message": "",
    "path": "/api/create-rfq"
}
Run Code Online (Sandbox Code Playgroud)

相反,我想要 "message": "User Not Found",

在一个阶段,我什至让它工作。好像我在某些点上搞砸了。

在日志中,您甚至可以看到 User Not Found 文本和正确的异常类

24 Jun 2020;20:50:52.998 DEBUG …
Run Code Online (Sandbox Code Playgroud)

service exception spring-mvc spring-restcontroller

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

415 spring应用程序中的POST请求不支持的MediaType

我有一个非常简单的Spring应用程序(不是弹簧启动).我已经实现了GET和POST控制器方法.该GET方法工作正常.但是在POST415 Unsupported MediaType.下面提供了重现步骤

ServiceController. java

package com.example.myApp.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


    @Controller
    @RequestMapping("/service/example")
    public class ServiceController {

        @RequestMapping(value="sample", method = RequestMethod.GET)
        @ResponseBody
    public String getResp() {
        return "DONE";
    }

    @RequestMapping(value="sample2", method = RequestMethod.POST, consumes = "application/json")
    @ResponseBody
    public String getResponse2(@RequestBody Person person) {
        return "id is " + person.getId();
    }

}

class Person {

    private int id;
    private String name;

    public Person(){

    }

    public int getId() …
Run Code Online (Sandbox Code Playgroud)

spring spring-mvc spring-restcontroller

12
推荐指数
2
解决办法
4万
查看次数