【问题标题】:spring does not reginase "redirect:/path" returning a simple stringspring 不会重新生成“redirect:/path”,返回一个简单的字符串
【发布时间】:2020-01-12 11:04:17
【问题描述】:

重定向只返回一个简单的字符串。它无法识别重定向。 响应只打印“redirect:/getUser/”
你能帮助我吗? 已经谢谢了。

the return should be the list of user with the new user added

@Slf4j
@RestController
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping(value = "/getUser", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public List<UserDTO> getUsers() throws Exception {
        List<UserDTO> oListUsers = new ArrayList<UserDTO>();

        try {
            oListUsers = userService.findAll();

        } catch (Exception ex) {
            log.error("Error getUsers. Cause: " + ex.getMessage());
            throw new Exception("Data can not be retrieved. Cause: " + ex.getMessage());
        }

        return oListUsers;
    }

    @PostMapping("/createUser")
    public String createUser(@Valid @RequestBody UserDTO newUser) throws Exception {

        try {
            userService.save(newUser);
        } catch (Exception ex) {
            log.error("Error createUser. Cause: " + ex.getMessage());
            throw new Exception("Data can not be save. Cause: " + ex.getMessage());
        }

        return "redirect:/getUser/";
    }
}

【问题讨论】:

  • createUser 方法未遵循 REST 。我建议它进行相应的更改并返回 ResponseEntity

标签: java spring-boot spring-mvc


【解决方案1】:

我建议进行以下更改。

@PostMapping("/user")
    public ResponseEntity createUser(@Valid @RequestBody UserDTO newUser) throws Exception {
       UserDTO createdUser;
        try {
            createdUser=userService.save(newUser);
        } catch (Exception ex) {
            log.error("Error createUser. Cause: " + ex.getMessage());
            throw new Exception("Data can not be save. Cause: " + ex.getMessage());
        }

        return new ResponseEntity(createdUser);
    }

并提供其他API来列出所有用户

【讨论】:

  • 谢谢Mandar,但是字符串没有办法处理吗(“return”redirect:/getUser/“)?
  • @LuisAntônioCostaFilho 是的,也可以使用字符串 ("return "redirect:/getUser/")?
  • 但不适用于我。只需打印字符串 url。
猜你喜欢
  • 2021-11-18
  • 1970-01-01
  • 2017-08-16
  • 2012-01-21
  • 2015-04-26
  • 2010-11-10
  • 2016-02-14
  • 1970-01-01
相关资源
最近更新 更多