Spring Mvc 中ModelAndView使用及json數(shù)據(jù)返回記載

一:好言

最重要的是一開(kāi)始的選擇,最難的是之后所有的堅(jiān)持

二、背景

最近開(kāi)始重構(gòu)之前的項(xiàng)目,說(shuō)實(shí)話這項(xiàng)目太渣了,從框架到代碼風(fēng)格,都是很差,最要命的是一行l(wèi)og都沒(méi)有,蒼天呀,代碼可讀性太差了。之前還是http的,所以今天開(kāi)始把項(xiàng)目改為分布式dubbo的。紀(jì)錄紀(jì)錄遇到的一點(diǎn)問(wèn)題。

三、內(nèi)容

3.1 、有的頁(yè)面既需要跳轉(zhuǎn)頁(yè)面可能另外一種情況需要返回?cái)?shù)據(jù),這個(gè)我首先想到的就是重定向,然后返回返回null,如果是值得花直接寫(xiě)json出去。
3.2 、我們經(jīng)常使用ModelAndView這個(gè)類(lèi),這個(gè)類(lèi)返回是可以帶對(duì)象跳轉(zhuǎn)頁(yè)面,那么我們可不可以根據(jù)返回類(lèi)型來(lái)做不同效果。所以我們可以重寫(xiě)ModelAndView中的getView方法
3.3 、 復(fù)寫(xiě)ModelAndView中的方法,具體代碼如下
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
public class JsonDataModelAndView extends ModelAndView {
    private Object objectJson;
    private  static  Gson gson = new Gson();
   
    public JsonModelAndView(Object objectJson){
        super();
        this.objectJson= objectjson;
    }

    @Override
    public View getView(){
        return new View() {
            @Override
            public String getContentType() {
                return "application/json;charset=utf-8";
            }

            @Override
            public void render(Map<String, ?> map, HttpServletRequest httpServletRequest, 
HttpServletResponse httpServletResponse) throws Exception {
                httpServletResponse.setContentType(getContentType());
                ServletOutputStream out =   httpServletResponse.getOutputStream();
                try
                {
                    if(objectJson != null)
                    {
                        String json = gson .toJson(objectjson);
                        byte[] byte = json.getBytes("utf-8");
                        out.write(byte );
                        out.flush();
                    }
                }finally
                {
                    if(out != null)
                    {
                        out.close();
                    }
                }
            }
        };
    }
}

返回json代碼


Map<String, Object> map = new HashMap<String, Object>();
map.put("flag", "123");
return  new JsonDataModelAndView (map )

結(jié)果如下圖所示


image.png

跳轉(zhuǎn),需要使用ModelAndView,如果自己頁(yè)面做了映射比如WEB-INF/view/index.jsp,那么下面的url可以換成index,會(huì)跳轉(zhuǎn)到index.jsp頁(yè)面

String url = "index";
return new ModelAndView(new RedirectView("https://www.baidu.com/"));

如果使用JsonDataModelAndView 則返回如下截圖


image.png
3.4、用流寫(xiě)json
JSONObject jsonObject=new JSONObject();
jsonObject.put("flag", "123");
jsonObject.put("name", "Mahone");
WriteJsonUtil.writeJson(jsonObject.toJSONString(),response);
public class WriteJsonUtil {
    public static void writeJson(Object object, HttpServletResponse response){
        response.setContentType("application/json" );
        try {
            response.getWriter().write(object.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
image.png
3.5、用注解返回json
    @ResponseBody
    @RequestMapping("test/{id}")
    public Map<String, Object> TEST(@PathVariable String id, HttpServletRequest req){
        return testService.test(id,req);
    }
    <mvc:annotation-driven />

如果你的類(lèi)是接口,那么你可以直接使用@RestController來(lái)做處理。這樣方法上不用寫(xiě) @ResponseBody

@RestController
public class TestController{

    @RequestMapping("test/{id}")
    public Map<String, Object> test(@PathVariable String id, HttpServletRequest req){
        return testService.test(id,req);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,034評(píng)論 25 709
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,554評(píng)論 19 139
  • 1、Spring MVC請(qǐng)求流程 (1)初始化:(對(duì)DispatcherServlet和ContextLoderL...
    拾壹北閱讀 2,016評(píng)論 0 12
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語(yǔ)法,類(lèi)相關(guān)的語(yǔ)法,內(nèi)部類(lèi)的語(yǔ)法,繼承相關(guān)的語(yǔ)法,異常的語(yǔ)法,線程的語(yǔ)...
    子非魚(yú)_t_閱讀 34,692評(píng)論 18 399
  • 本人雖然是北漂一族,但現(xiàn)在不是什么所謂的傻白甜,也算是人精了,知道上司的心思了,我們那兒來(lái)一小姑娘,也算是...
    7魘閱讀 358評(píng)論 0 1

友情鏈接更多精彩內(nèi)容