SpringMVC跨域接收JSON

#編者注
因爲要編寫一個統一的xmlrpc調用與rest,裏面涉及到了跨域調用問題。隨即有如下內容javascript

#Spring的跨域
##Spring 4.2.x 編者本來是想在Spring響應內容添加跨域請求,但因爲很差劃定跨域範圍,產生了拆分想法。但通過查詢Spring文檔後發現,最新穩定版本提供了跨域支持**@CrossOrigin**,隨即咱們就能夠在Controller當中添加註解來完成。css

@Controller
@RequestMapping(value = "/default/Api")
public class XmlrpcServerController {

    @CrossOrigin
    @RequestMapping(method = RequestMethod.POST)
    public Object xmlrpc_api(@RequestBody String body) throws Exception {

        //get body
        System.out.println(body);

        //doing

        return result;
    }

#JSON信息的接收 除了咱們要接收上面需求的xml文件之外,rest接收還應當包括其餘對象。經過搜索發現須要經過ajax把json以data的形式進行發送。html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap 101 Template</title>

    <!-- Bootstrap -->
    <link href="http://localhost:8080/resources/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
    <script src="//cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="//cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
</head>
<body>
<h1>你好,世界!</h1>
<script type="text/javascript">
    function myFunction()
    {

        var json = "{ \"username\":\"admin\", \"password\":\"yanfa\" }";
        $.ajax({
            type:"POST",
            url:"http://localhost:8080/tactic/ticket",
            dataType:"json",
            contentType:"application/json",
            data:json,
            success : function(data) {
                alert("新增成功!" + data);
            },
            error : function(data) {
                alert(data)
            }
        });
    }
</script>

<a class="btn btn-default" role="button" onclick="myFunction()">Link</a>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="http://localhost:8080/resources/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>
相關文章
相關標籤/搜索