简体   繁体   English

从html页面调用REST Web服务spring控制器,并使用ajax将表单元素与调用一起单独传递

[英]Calling a REST web service spring controller from a html page, and passing the form elements alone with the call using ajax

I have a controller that creates a new user for my application (users are stored using MongoDB). 我有一个为我的应用程序创建新用户的控制器(用户使用MongoDB存储)。 I ran the code with @Path and @RequestBody annotations successfully using postman tool. 我使用邮差工具成功运行了带有@Path和@RequestBody批注的代码。

Now I have to include a UI which is mapped to my controller. 现在,我必须包含一个映射到我的控制器的UI。 I tried passing the values using ajax, and the values are getting passed(upon inspection from my browser). 我尝试使用ajax传递值,并且传递值(通过浏览器检查)。 But the controller is not being called. 但是没有调用控制器。

Then I tried with @RequestMapping and @RequestBody annotations but then I am getting the following warning while accessing it through Postman WARNING: No root resource matching request path /Task1_2/Create/createUser has been found, Relative Path: /Create/createUser. 然后,我尝试使用@RequestMapping@RequestBody批注,但是通过邮递员访问它时收到以下警告警告:找不到与请求路径/ Task1_2 / Create / createUser匹配的根资源,相对路径:/ Create / createUser。

Finally, I tried with all three annotations @Path , @RequestMapping and @RequestBody then I am getting a response in Postman. 最后,我尝试使用@ @Path ,@ @RequestMapping@RequestBody这三个批注,然后在Postman中得到响应。

All the above were done by directly calling the controller from Postman through the URI. 以上所有操作都是通过URI直接从Postman调用控制器来完成的。

But still, now I am not able to get any response on my browser while calling the HTML page which is mapped to my controller. 但是,现在仍然无法在调用映射到控制器的HTML页面时在浏览器上获得任何响应。

This is my controller 这是我的控制器

@RestController

@Path("/Create/")
@RequestMapping("/Create/")
public class CreateUser {
    @POST
    @Path("createUser")
    @RequestMapping(value="createUser",method=RequestMethod.POST,consumes="application/json")
    public Response Create(@RequestBody String request)
    {
    ..... 
    BasicDBObject obj = (BasicDBObject) JSON.parse(request);
    .....
    output = "@Produces(\"application/json\")"+"User Created Successfully";
    return Response.status(200).entity(output).build();
    }

And this is my ajax function 这是我的ajax功能

function fun()
        {
            var search = {  UserName: $( "input[name='UserName']" ).val(), 
                            FirstName: $( "input[name='FirstName']" ).val(), 
                            LastName: $( "input[name='LastName']" ).val(),
                            Mobile: $( "input[name='Mobile']" ).val(),
                            EmailId: $( "input[name='Email']" ).val()
                    }
           $.ajax({
              type: "POST",
              contentType : 'application/json; charset=utf-8',
              dataType : 'json',
              url: "/Create/createUser",
              data: JSON.stringify(search), // Note it is important
              success :function(output) {
                  alert(output);
              },
              error: function(e){
                  alert('failure');
              }
          });
        }

I have kept the HTML file(CreateUser.html) with the above script inside the WebContent folder of my project. 我将带有以上脚本的HTML文件(CreateUser.html)保留在项目的WebContent文件夹中。 So 1. What am I doing wrong? 所以1.我做错了什么? 2. Should I be using @Path alone with @RequestMapping 2.我应该单独使用@Path和@RequestMapping吗?

I think it is related to your JSON format which your are sending from Ajax. 我认为这与从Ajax发送的JSON格式有关。

This would run 这将运行

function fun()
        {
            var search = {  UserName: $( "input[name='UserName']" ).val(), 
                            FirstName: $( "input[name='FirstName']" ).val(), 
                            LastName: $( "input[name='LastName']" ).val(),
                            Mobile: $( "input[name='Mobile']" ).val(),
                            EmailId: $( "input[name='Email']" ).val()
                    }
           $.ajax({
              type: "POST",
              contentType : 'application/json; charset=utf-8',
              dataType : 'json',
              url: "/Create/createUser",
              data: JSON.stringify({search : search }), // Note it is important
              success :function(output) {
                  alert(output);
              },
              error: function(e){
                  alert('failure');
              }
          });
        }

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

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