Ajax发布Spring MVC控制器?

时间:2017-07-06 08:07:40

标签: java jquery ajax spring spring-mvc

我正在尝试使用Spring Boot,并希望对Spring Controller进行Ajax POST。我是从POSTMAN测试的,但后来我一直收到这个错误。它似乎不是发布到我的控制器,而是寻找名为jsondata.jsp的视图。我该如何解决这个问题?

{
    "timestamp": 1499255141424,
    "status": 404,
    "error": "Not Found",
    "message": "/WEB-INF/view/jsondata.jsp",
    "path": "/jsondata"
}

IndexController.java
package com.example.demo;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
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.RequestParam;
import org.springframework.web.client.RestTemplate;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;



    @Controller
    public class IndexController {

        @Autowired
        private WelcomeService service;
        @RequestMapping("/")
        public String home(Map<String, Object> model) {
            String msg = service.retrieveWelcomeMessage();
            model.put("message",msg);
            return "index";
        }

        @RequestMapping("/next")
        public String next(Map<String, Object> model) {
            model.put("message", "You are in new page !!");
            return "next";
        }

        @RequestMapping(value = "/jsondata", method = RequestMethod.POST,consumes = "application/json")
        public String getfeeddata(@RequestBody String info,Map<String, Object> model)
        {
            model.put("info", info);
            return "next";
        }

        @Component
        class WelcomeService {

            public String retrieveWelcomeMessage() {
                //Complex Method
                 String msgType="";
                 RestTemplate restTemplate = new RestTemplate();
               String consumeJSONString = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", String.class);
               Gson gson = new GsonBuilder().create();
                Quote r = gson.fromJson(consumeJSONString, Quote.class);
                msgType=r.getValue().getQuote();
                return msgType;
            }


        }

    }

MVCConfiguration.java
    package com.example.demo;

    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    import org.springframework.web.servlet.view.InternalResourceViewResolver;
    import org.springframework.web.servlet.view.JstlView;

    @Configuration
    @EnableWebMvc
    @ComponentScan
    public class MvcConfiguration extends WebMvcConfigurerAdapter
    {
        @Override
        public void configureViewResolvers(ViewResolverRegistry registry) {
            InternalResourceViewResolver resolver = new InternalResourceViewResolver();
            resolver.setPrefix("/WEB-INF/view/");
            resolver.setSuffix(".jsp");
            resolver.setViewClass(JstlView.class);
            registry.viewResolver(resolver);
        }
    }

View
<!DOCTYPE html>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html lang="en">
<body>
<head>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script type="text/javascript">
        $(document).ready(function() {
            $('#submit').click(function ()
            {
                var info =[];
                info.push("JsonPostdata");
                $.ajax({
                    type: "post",
                    url: "/jsondata", 
                    data: JSON.stringify(info),
                    success: function(msg){      
                        console.log("success");
                    }
                });
            });

        });
    </script>
</head>
    <div>
        <div>
            <h1>Spring Boot JSP Example</h1>
            <form >
              <input type="submit" id ="submit" value="Not clicked">

            </form>
            <h2>Hello ${message}</h2>

            Click on this <strong><a href="next">link</a></strong> to visit another page.
        </div>
    </div>


</body>
</html>

1 个答案:

答案 0 :(得分:1)

这是application/json方法的样子。

@RequestMapping(value = "jsondata", method = RequestMethod.POST, headers="Content-Type=application/json")
public @ResponseBody String post(@RequestBody String string) {
            //process your "string" here
            //instead of string you can use other object or array of objects also. 
            return string;
}

您要做的是将字符串添加到model。然后,如果您返回一个字符串“next”,那么控制器将查找next.jsp。那你不想要对吗?