国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

SpringMVC 的 Controller 返回各種視圖的處理方式

2019-11-15 00:43:36
字體:
供稿:網(wǎng)友
SPRingMVC 的 Controller 返回各種視圖的處理方式

SpringMVC 的 Controller 可以返回各種各樣的視圖。比如 jsp, JSON, Velocity, FreeMarker, xml, PDF, Excel, 還有Html字符流 等等。那它們?cè)撊绾蔚倪M(jìn)行處理的呢?這里就涉及到 各種視圖(View)對(duì)應(yīng)的各種視圖解析器(ViewResolver). 基本上上面說的每一種視圖就對(duì)應(yīng)用一種視圖解析器來處理?;旧细鞣N視圖解析器大致上可以分為兩類:一是基于URL的視圖解析器;一種是其它解析器;所謂的UrlBasedViewResolver,就是將返回值作為最終視圖的url的一部分,然后和相關(guān)配置組合起來,就是最終的視圖地址url. 我們看下UrlBasedViewResolver的解析器有哪些:

1. 返回JSP

返回JSP是最簡單的,JSP視圖的視圖解析器為 InternalResourceViewResolver,也是一個(gè)UrlBasedViewResolver解析器。其對(duì)應(yīng)的解析器的配置一般如下:

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>    <property name="prefix" value="/WEB-INF/jsp/"/>    <property name="suffix" value=".jsp"/></bean>

使用該例子,我們好好理解下什么是 “基于URL” 的視圖解析器,比如我們的 Controller 中最后的返回的處理代碼為: return "index"; 那么“基于URL” 的視圖解析器就會(huì)將返回值 “index” 作為最后視圖的URL的一部分,然后結(jié)合上面的配置 <property name="prefix" value="/WEB-INF/jsp/"/> 和 <property name="suffix" value=".jsp"/>,最后得到最終的URL: "/WEB-INF/jsp/" + "index" + ".jsp" == "/WEB-INF/jsp/index.jsp"

這就是所謂的 “基于URL” 的視圖解析器的工作方式。

2. 返回 HTML 頁面

我們知道在Servlet中,我們是可以直接在其中打印輸出HTML字符流到最終頁面,比如下面的代碼來自阿里巴巴的支付寶的接入示例中的代碼:

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        request.setCharacterEncoding("utf-8");        response.setCharacterEncoding("utf-8");                        // ... ...                //建立請(qǐng)求        String sHtmlText = Al
    /**     * 建立請(qǐng)求,以表單HTML形式構(gòu)造(默認(rèn))     * @param sParaTemp 請(qǐng)求參數(shù)數(shù)組     * @param strMethod 提交方式。兩個(gè)值可選:post、get     * @param strButtonName 確認(rèn)按鈕顯示文字     * @return 提交表單HTML文本     */    public static String buildRequest(Map<String, String> sParaTemp, String strMethod, String strButtonName) {        //待請(qǐng)求參數(shù)數(shù)組        Map<String, String> sPara = buildRequestPara(sParaTemp);        List<String> keys = new ArrayList<String>(sPara.keySet());        StringBuffer sbHtml = new StringBuffer();        sbHtml.append("<!doctype html><html><head><meta http-equiv=/"Content-Type/" content=/"text/html; charset=UTF-8/">");        sbHtml.append("<title>支付寶即時(shí)到賬交易接口</title></head><body>");        sbHtml.append("<form id=/"alipaysubmit/" name=/"alipaysubmit/" action=/"" + ALIPAY_GATEWAY_NEW                      + "_input_charset=" + AlipayConfig.input_charset + "/" method=/"" + strMethod                      + "/">");        for (int i = 0; i < keys.size(); i++) {            String name = (String) keys.get(i);            String value = (String) sPara.get(name);            sbHtml.append("<input type=/"hidden/" name=/"" + name + "/" value=/"" + value + "/"/>");        }        //submit按鈕控件請(qǐng)不要含有name屬性        sbHtml.append("<input type=/"submit/" value=/"" + strButtonName + "/" style=/"display:none;/"></form>");        sbHtml.append("<script>document.forms['alipaysubmit'].submit();</script>");        sbHtml.append("</body></html>");        return sbHtml.toString();    }

很顯然,Servlet直接將HTML的字符流輸出到了瀏覽器端,那么在SpringMVC中該如何做呢?其實(shí)在SpringMVC中我們也是可以如下實(shí)現(xiàn)的:

    @RequestMapping(value="/getPage")    public void writeSubmitHtml(Reader reader, Writer writer, Httpsession session) throws IOException {        User user = (User) session.getAttribute(ConstantConfig.LONGIN_USER);        StringBuffer sbHtml = new StringBuffer();        sbHtml.append("<!doctype html><html><head><meta http-equiv=/"Content-Type/" content=/"text/html; charset=UTF-8/">");        sbHtml.append("<title>支付寶即時(shí)到賬交易接口</title></head><body>"+ user.getNo() +"</body></html>");        writer.write(sbHtml.toString());      }

我們看到我們直接使用了參數(shù) Writer writer,返回值為 void, 其實(shí)參數(shù) Writer writer 也可以換成 PrintWriter writer; 直接寫出HTML的字符流。

我們也知道在Servlet中,我們是可以直接forward或者redirecit到html頁面,所以我們也可以如下在springmvc中返回到html頁面:

    @RequestMapping(value="/htmlView")    public void htmlView(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{        // ...        request.getRequestDispatcher("index.html").forward(request, response);     //response.sendRedirect("http://www.baidu.com");    }

這里,我們體會(huì)到了:springmvc他是建立在servlet之上的,所以在servlet中能夠做到的,同樣在springmvc一樣有效。

3. 返回JSON格式

返回JSON格式在SpringMVC中有多種處理方式,一種是使用SpirngMVC自帶的 MappingJackson2JsonView 來處理,一種是自己寫代碼將返回值JSON格式化,然后直接用PrintWrite類型的對(duì)象寫出就行了。

1)直接用PrintWrite類型的對(duì)象寫出JSON格式

    @RequiresRoles(value={"student"})    @RequestMapping(value="/queryScoreForStudent")    public void queryScoreForStudent(ScoreQueryParam param, HttpSession sesion, PrintWriter printWriter){        Student student = (Student)sesion.getAttribute(ConstantConfig.LONGIN_STUDENT);        param.setStudentId(student.getId());        PageBean<StudentScore> scoreList = this.studentCourseService.queryScoreForStudent(param);        if(scoreList != null && scoreList.getSize() > 0){            Map<String, Object> map = new HashMap<>();            map.put("result", "ok");            map.put("data", scoreList);            printWriter.write(JSON.toJSONString(map));        }    }

如上代碼所示,我們?cè)诜椒ㄖ屑尤肓?PrintWriter printWriter 參數(shù),最后的返回結(jié)果使用了fastjson庫來格式化最后的返回的對(duì)象map. 然后使用printWriter寫出,就行了。我們看到方法上的注解并沒有使用 @ResponseBody. 當(dāng)然最好這里是在方法上加上 @ResponseBody,但是因?yàn)榉祷氐膍ap已經(jīng)是JSON格式的,所以并不需要配置 MappingJackson2JsonView !

2)使用MappingJackson2JsonView 配合@ResponseBody來返回JSON格式

首先需要進(jìn)行相關(guān)的視圖解析器的配置:

     <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">        <property name="mediaTypes">            <map>                <entry key="atom" value="application/atom+xml"/>                <entry key="html" value="text/html"/>                <entry key="json" value="application/json"/>            </map>        </property>        <property name="viewResolvers">            <list>                <!-- <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/> -->                <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">                    <property name="prefix" value="/"/>                    <property name="suffix" value=".jsp"/>                </bean>            </list>        </property>        <property name="defaultViews">            <list>                <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" />            </list>        </property>    </bean>

這里用到了 ContentNegotiatingViewResolver ,“內(nèi)容協(xié)商視圖解析器”,其實(shí)就是根據(jù)返回什么類型的視圖,就協(xié)商使用哪種視圖解析器。如果返回jsp就使用InternalResourceViewResolver視圖解析器,如果返回JSON格式就使用MappingJackson2JsonView來處理。如此而已。在 <property name="viewResolvers"> 下的<list> 標(biāo)簽下,還可以加入其他的各種視圖解析器的配置。

配置了MappingJackson2JsonView 之后,就沒有必要在自己手動(dòng) JSON格式化了,上面的例子,可以改成:

    @RequiresRoles(value={"student"})    @RequestMapping(value="/queryScoreForStudent")    @ResponseBody    public Map<String, Object> queryScoreForStudent(ScoreQueryParam param, HttpSession sesion){        Student student = (Student)sesion.getAttribute(ConstantConfig.LONGIN_STUDENT);        param.setStudentId(student.getId());        PageBean<StudentScore> scoreList = this.studentCourseService.queryScoreForStudent(param);        System.out.println(JSON.toJSONString(scoreList));        if(scoreList != null && scoreList.getSize() > 0){            Map<String, Object> map = new HashMap<>();            map.put("result", "ok");            map.put("data", scoreList);            return map;        }    }

其他格式Velocity, FreeMarker, XML, PDF, Excel等視圖的處理,后面有時(shí)間在補(bǔ)上。


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 鲁山县| 龙岩市| 孙吴县| 慈利县| 苍南县| 颍上县| 江孜县| 威宁| 民丰县| 双峰县| 东台市| 喀喇沁旗| 宁明县| 小金县| 古田县| 大丰市| 蕉岭县| 昌图县| 日土县| 乌兰县| 永嘉县| 阜南县| 吴旗县| 日喀则市| 丹寨县| 荣成市| 安顺市| 印江| 简阳市| 闻喜县| 万州区| 石林| 双城市| 深州市| 桑植县| 乌鲁木齐市| 衡东县| 宁远县| 商水县| 无极县| 荣成市|