博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring MVC自定义视图实现jsonp
阅读量:7078 次
发布时间:2019-06-28

本文共 7776 字,大约阅读时间需要 25 分钟。

hot3.png

约定的优先级规则:

Spring supports a couple of conventions for selecting the format required: URL suffixes and/or a URL parameter. These work alongside the use of Accept headers. As a result, the content-type can be requested in any of three ways. By default they are checked in this order:Add a path extension (suffix) in the URL. So, if the incoming URL is something likehttp://myserver/myapp/accounts/list.html then HTML is required. For a spreadsheet the URL should be http://myserver/myapp/accounts/list.xls. The suffix to media-type mapping is automatically defined via the JavaBeans Activation Framework or JAF (so activation.jar must be on the class path).A URL parameter like this: http://myserver/myapp/accounts/list?format=xls. The name of the parameter is format by default, but this may be changed. Using a parameter is disabled by default, but when enabled, it is checked second.Finally the Accept HTTP header property is checked. This is how HTTP is actually defined to work, but, as previously mentioned, it can be problematic to use.

spring-web.xml配置:

    
    
    
    
    
    
    
    
    
        
            
            
            
        
        
    
    
    
    
    
        
            
            
        
        
    
        
/
        
        
.jsp
    

json和jsonp视图类:

package com.caiya.test;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.alibaba.fastjson.serializer.JSONSerializer;import com.alibaba.fastjson.serializer.SerializerFeature;import org.apache.commons.lang3.StringUtils;import org.springframework.util.CollectionUtils;import org.springframework.validation.BindingResult;import org.springframework.web.servlet.view.AbstractView;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.ByteArrayOutputStream;import java.io.OutputStream;import java.nio.charset.Charset;import java.util.HashMap;import java.util.Map;import java.util.Set;/** * Created by caiya on 16/2/1. */public class ExtendedJsonView extends AbstractView {    public static final String  DEFAULT_CONTENT_TYPE = "application/json";    public final static Charset UTF8                 = Charset.forName("UTF-8");    private Charset             charset              = UTF8;    private SerializerFeature[] serializerFeatures    = new SerializerFeature[0];    private Set
 renderedAttributes;    private boolean             disableCaching       = true;    private boolean             updateContentLength  = false;    public ExtendedJsonView(){        setContentType(DEFAULT_CONTENT_TYPE);        setExposePathVariables(false);    }    public void setRenderedAttributes(Set
 renderedAttributes) {        this.renderedAttributes = renderedAttributes;    }    @Deprecated    public void setSerializerFeature(SerializerFeature... features) {        this.setFeatures(features);    }    public Charset getCharset() {        return this.charset;    }    public void setCharset(Charset charset) {        this.charset = charset;    }    public SerializerFeature[] getFeatures() {        return serializerFeatures;    }    public void setFeatures(SerializerFeature... features) {        this.serializerFeatures = features;    }    @Override    protected void renderMergedOutputModel(Map
 model, HttpServletRequest request,                                           HttpServletResponse response) throws Exception {        Object value = filterModel(model);        String text = JSON.toJSONString(value, serializerFeatures);        String callback = request.getParameter("callback");        if(StringUtils.isNotBlank(callback)){            text = new StringBuilder(callback).append("(").append(text).append(")").toString();        }        byte[] bytes = text.getBytes(charset);        OutputStream stream = this.updateContentLength ? createTemporaryOutputStream() : response.getOutputStream();        stream.write(bytes);        if (this.updateContentLength) {            writeToResponse(response, (ByteArrayOutputStream) stream);        }    }    @Override    protected void prepareResponse(HttpServletRequest request, HttpServletResponse response) {        setResponseContentType(request, response);        response.setCharacterEncoding(UTF8.name());        if (this.disableCaching) {            response.addHeader("Pragma", "no-cache");            response.addHeader("Cache-Control", "no-cache, no-store, max-age=0");            response.addDateHeader("Expires", 1L);        }    }    /**     * Disables caching of the generated JSON.     * 

     * Default is {@code true}, which will prevent the client from caching the generated JSON.     */    public void setDisableCaching(boolean disableCaching) {        this.disableCaching = disableCaching;    }    /**     * Whether to update the 'Content-Length' header of the response. When set to {@code true}, the response is buffered     * in order to determine the content length and set the 'Content-Length' header of the response.     * 

     * The default setting is {@code false}.     */    public void setUpdateContentLength(boolean updateContentLength) {        this.updateContentLength = updateContentLength;    }    /**     * Filters out undesired attributes from the given model. The return value can be either another {@link Map}, or a     * single value object.     * 

     * Default implementation removes {@link BindingResult} instances and entries not included in the     * {@link #setRenderedAttributes(Set) renderedAttributes} property.     *     * @param model the model, as passed on to {@link #renderMergedOutputModel}     * @return the object to be rendered     */    protected Object filterModel(Map

 model) {        Map
 result = new HashMap
(model.size());        Set
 renderedAttributes = !CollectionUtils.isEmpty(this.renderedAttributes) ? this.renderedAttributes : model.keySet();        for (Map.Entry
 entry : model.entrySet()) {            if (!(entry.getValue() instanceof BindingResult) && renderedAttributes.contains(entry.getKey())) {                result.put(entry.getKey(), entry.getValue());            }        }        return result;    }}

测试controller:

package com.caiya.test.controllers;import org.apache.log4j.Logger;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.RestController;import org.springframework.web.servlet.ModelAndView;import javax.annotation.Resource;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServletResponse;import java.util.HashMap;import java.util.Map;/** * Created by caiya on 16/1/28. */@Controller@RequestMapping(value = "/test")public class TestController {    private static final Logger logger = Logger.getLogger(TestController.class);    @RequestMapping(value = {"/test2.json"})    public Object test2(){        Map
 map = new HashMap
();        map.put("key", "value");        return map;    }    @RequestMapping(value = {"/test2"}, produces = {"application/json"})    public Object test22(){        Map
 map = new HashMap
();        map.put("key", "value");        return map;    }    @RequestMapping(value = {"/test2"}, produces = {"text/html"})    public Object test222(){        return "cookie";    }}

效果图:

160810_89ZC_576855.png

160810_ZCOo_576855.png

160811_TKKt_576855.png

161831_1Mns_576855.png

161832_xsr2_576855.png

161832_JCGJ_576855.png

--------------------------------------

转载于:https://my.oschina.net/wnjustdoit/blog/612638

你可能感兴趣的文章
从 CentOS 5.5 中精简出属于自己的专属Linux (三)
查看>>
C和指针---第十五章:输入/输出函数
查看>>
Linux打开txt文件乱码的解决方法
查看>>
腾讯微博android授权 SharedPreferences用法
查看>>
图文详解YUV420数据格式
查看>>
nginx 【logformat】日志格式
查看>>
【Linux系列】【基础版】第四章 Shell基础之正则表达式
查看>>
JWT 在 Spring 上的实践
查看>>
释放linux缓存
查看>>
4、C语言 —— 基本运算
查看>>
js判断是否是ipad还是iphone及各手机用户
查看>>
同时添加多个github ssh key的方法
查看>>
Essential Grid for ASP.NET MVC
查看>>
PDA使用异常指导手册
查看>>
goroutine背后的系统知识
查看>>
ubuntu安装nrpe无法安装问题
查看>>
命令操作
查看>>
SAN 光纤交换机配置远距离级联(EF)操作
查看>>
Web性能优化方案
查看>>
关于proteus闪退问题
查看>>