SpringMVC通过视图配置器返回Json和跨域Jsonp格式数据

上接SpringMVC+jetty框架搭建

 

1、首先要配置视图配置器,见前面文章SpringMVC+jetty框架搭建

 

2、jsonp数据格式转换器

package com.suning.viewsolver;


import java.util.Map;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.springframework.web.servlet.view.AbstractView;


import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;




public class JsonpView extends AbstractView{
public static final String DEFAULT_CONTENT_TYPE = "application/javascript";


public JsonpView() {
super();
setContentType(DEFAULT_CONTENT_TYPE);
}


private ObjectMapper objectMapper = new ObjectMapper();


@Override
protected void prepareResponse(HttpServletRequest request, HttpServletResponse response) {
super.prepareResponse(request, response);
response.setHeader("Content-Type", getContentType() + "; charset=UTF-8");
}


@Override
protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
String callback = request.getParameter("callback");
JsonGenerator generator = null;
try {
generator = objectMapper.getJsonFactory().createJsonGenerator(response.getOutputStream(), JsonEncoding.UTF8);
if (callback != null) {
generator.writeRaw(callback + "( ");
}


objectMapper.writeValue(generator, model);
if (callback != null) {
generator.writeRaw(" );");
}


generator.flush();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
generator.close();
} catch (Exception e) {
}
}
}
}

 

3、测试类

package com.suning.service;


import java.util.HashMap;
import java.util.Map;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.suning.viewsolver.Account;


@Controller
public class PsServiceApp {
private Logger log = LoggerFactory.getLogger(PsServiceApp.class);
ModelAndView mav = new ModelAndView();
Account account = new Account();
@RequestMapping(value = "/change_version.do", produces = "application/json; charset=UTF-8")
    public void changeVersion(@RequestParam("version") String version, HttpServletResponse response)
    throws Exception{
    JSONObject json = new JSONObject();
        response.setContentType("application/json;charset=UTF-8");
   
    String result = version;
    json.put("result", result);
        json.writeJSONString(response.getWriter());
    return;
    }
/*
* 解析Json方式一:使用JSON工具将对象序列化成json,常用工具Jackson,fastjson,gson。
* 利用HttpServletResponse,然后获取response.getOutputStream()或response.getWriter(),直接输出*/
@RequestMapping("/test.json")
public void testDemo(HttpServletRequest request, HttpServletResponse response) {
        String q = request.getParameter("q");
        if (StringUtils.isEmpty(q)) {
            q = "输入为空";
            writeResponseParse(response, q);
            return;
        }
        q = "json解析"+q;
        writeResponseRes(response, q);
    }
/*
* 方式二:非注解形式,配置JsonView视图,.json结尾的url以Json格式返回数据*/
@RequestMapping(value = "/test2.json")  
public ModelAndView queryAppliesForJson(HttpServletRequest request) {  
String q = request.getParameter("q");
        if (StringUtils.isEmpty(q)) {
            q = "输入为空";
        }
        account.setId(q);
        mav.addObject(account);
   return mav;  
}  

/*
* 方式二:非注解形式,配置JsonView视图,.jsonp结尾的url以Jsonp格式返回数据*/
@RequestMapping(value = "/test3.jsonp")  
public Map queryAppliesForJsonp() {  
Map map = new HashMap(); 
   map.put("account","aa");  
   return map;  
}  
private void writeResponseParse(HttpServletResponse resp, String queryString) {
        try {
            // 设置编码类型、内容格式
            resp.setCharacterEncoding("utf-8");
            resp.setContentType("text/html;charset=utf-8");


            String res = "\"res\":" + JSON.toJSONString(queryString);
            String jsonString = "{" +res +"}";


            resp.getWriter().write(jsonString);
        } catch (Exception e) {
            log.error("返回json数据异常!", e);
        }
    }
private void writeResponseRes(HttpServletResponse resp, String queryResult) {
        try {
            // 设置编码类型、内容格式
            resp.setCharacterEncoding("utf-8");
            resp.setContentType("text/html;charset=utf-8");


            String res = "\"res\":" + JSON.toJSONString(queryResult);
            String jsonString = "{" +res +"}";


            resp.getWriter().write(jsonString);
        } catch (Exception e) {
            log.error("返回json数据异常!", e);
        }
    }
}

 

4、

(1)json测试

输入:

http://localhost:9080/ps_service/test.json?q=手机

输出:

{"res":"json解析手机"}

输入:

http://localhost:9080/ps_service/test2.json?q=17061434

得到

 

{"account":{"id":"17061434","userName":null}}

 

 

 

(2)jsonp测试:

输入:

http://localhost:9080/ps_service/test3.jsonp?callback=myfunc

输出:

 

myfunc( {"account":"aa"} );

 

 

 

输入:

http://localhost:9080/ps_service/test3.jsonp

输出:

 

{"account":"aa"}

 

 

 

你可能感兴趣的:(Spring)