简体   繁体   English

Spring Boot @RestController没有响应

[英]Spring Boot @RestController no respond

I'm starting with Spring and REST application. 我从Spring和REST应用程序开始。 Currently, I'm developing one application on my own and I stuck. 目前,我正在自行开发一个应用程序,但遇到了麻烦。

The app is divided just like standard Spring Boot project. 该应用程序像标准的Spring Boot项目一样被划分。 All of the controllers are contained in web package. 所有控制器都包含在web软件包中。 One of "standard" controller is responsible for handling HTTP request and returning an HTML website. “标准”控制器之一负责处理HTTP请求并返回HTML网站。 I have added a REST controller which should respond to POST request from the first controller, but I receive a 404 error. 我添加了一个REST控制器,该控制器应响应第一个控制器的POST请求,但收到404错误。

How it looks like in code? 在代码中看起来如何?

@RestController
@RequestMapping("/users")
public class UserRestController {
    @Autowired
    private UserService userService;


    @RequestMapping(value = "/user", method = RequestMethod.POST,  consumes = "application/json", produces = "application/json")
    public ResponseEntity<?> getUser(@RequestParam("userId") String userId, Errors errors) {
        AjaxUser response = new AjaxUser();

        if (errors.hasErrors()) {
            response.message = errors.getAllErrors().stream().map(x -> x.getDefaultMessage()).collect(Collectors.joining(","));

            return ResponseEntity.badRequest().body(response);

        }

        response.setUser(userService.getUserById(Integer.getInteger(userId).intValue()));

        return ResponseEntity.ok(response);

    }

    private class AjaxUser {
        private User user;
        private String message;

        public void setUser(User user) {
            this.user = user;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public String getMessage() {
            return message;
        }

        @Override
        public String toString() {
            return "User { id:" + user.getId() + ", Name: " + user.getName() + ", surname: " + user.getSurname() + "}";
        }
    }
}

From .js file I send a ajax query which should trigger a rest controller, here is the code: 从.js文件中,我发送了一个ajax查询,该查询应触发rest控制器,这是代码:

function sendUserId(id) {
    var user = {};
    user["userId"] = id;

    console.log("USER: ", user);

    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: "/users/user",
        data: JSON.stringify(user),
        dataType: 'json',
        cache: false,
        timeout: 100000,
        success: function (user) {

            var json = "<h4>Ajax Response</h4><pre>"
                + JSON.stringify(user, null, 4) + "</pre>";

            console.log("SUCCESS : ", user);

        },
        error: function (e) {

            var json = "<h4>Ajax Response</h4><pre>"
                + e.responseText + "</pre>";

            console.log("ERROR : ", e);
        }
    });
}

userId is taken from a html by jQuery, console.log show existing and right value. userId是jQuery取自html的, console.log显示现有值和正确值。

Note: There exist a standard user @Controller which is responsible for displaying a user list, it works, problem appear during sending a user id to REST controller. 注意:存在一个标准用户@Controller ,它负责显示用户列表,它可以正常工作,在将用户ID发送到REST控制器期间会出现问题。 It behaves just like the REST controller doesn't exist and browser return 404 status response . 它的行为就像REST控制器不存在,浏览器返回404 status response Btw, page use a Spring Secure to login and so on. 顺便说一句,页面使用Spring Secure进行登录等等。

Could someone help? 有人可以帮忙吗?

BR Konrad 康拉德

控制器正在寻找js请求网址中缺少的请求参数

/users/user?userId=1

You can get a user by id like below: 您可以通过以下ID获得用户:

@RequestMapping(value = "{id}", method = RequestMethod.GET)
public ResponseEntity<User> get(@PathVariable("id") int id) {
User user = userService.findById(id);

if (user == null) {
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}

return new ResponseEntity<User>(user, HttpStatus.OK);
}

So your rest entry point is /users/userid, eg: /users/1 因此,您的其余入口点是/ users / userid,例如:/ users / 1

Found this from the post Spring MVC RESTFul Web Service CRUD Example Spring MVC RESTFul Web Service CRUD示例帖子中找到了这一点

the problem based on function arguments, REST controller should take String argument and next parse it to JSON object, the response should be String too. 基于函数参数的问题,REST控制器应使用String参数,然后将其解析为JSON对象,响应也应为String。 Topic can be closed, thanks all to be involved. 话题可以结束,谢谢大家的参与。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM