(4)发布接口

2017-05-19  本文已影响0人  maomizone

只是写了最简单的测试下

springMvc的@ResponseBody可以直接输出json数据

网页调用接口木有问题,但是手机调用却出现跨域问题,必须要用jsonp实现,后台实现是getUser()方法

package com.djy.controller;

import com.djy.model.User;
import com.google.gson.Gson;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * Created by admin on 2017/5/19.
 */
@Controller
public class MainController {
    /**
     * @return 处理完该请求后返回的页面,此请求返回 index.jsp页面
     * @RequestMapping()注解:用于定义一个请求映射,value为请求的url,值为 / 说明,该请求首页请求,method用以指定该请求类型,一般为get和post;
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index() {
        return "index";
    }

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello() {
        return "hello";
    }



    @RequestMapping(value = "/data", method = RequestMethod.GET)
    public  @ResponseBody String data(){
        return "djy33333";
    }

    @RequestMapping(value = "/userJson", method = RequestMethod.GET)
    public  @ResponseBody User getUserJson(){
        User u = new User("djy", "13072520860", "123456");
        return u;
    }

    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public  @ResponseBody String getUser(String callback){
        User u = new User("djy", "13072520860", "123456");
        Gson gson = new Gson();
        if(callback == null)
            return gson.toJson(u);
        else
            return callback + "(" + gson.toJson(u) +")";

    }

}

对应的jquery代码

function loginReq() {
    $.ajax({
            url: 'http://192.168.0.164:8081/user',
        type: 'get',
        dataType: 'jsonp',
        jsonpCallback: "loginCallback",
        success: function(res) {
            alert("success");
            location.href = "index.html" + "?title= " + res.name + " ";
            return false;
        },
        error: function(error) {
            alert("error");
        }

    })

}

function loginCallback(json) {
    alert(json.name + "你好!");
}
上一篇下一篇

猜你喜欢

热点阅读