1. 程式人生 > 實用技巧 >SpringMvc返回html頁面字串

SpringMvc返回html頁面字串

需求:controller返回瀏覽器會渲染的html頁面字串

1.實現方式一

直接通過HttpServletResponse以流的方式將html字串寫到瀏覽器頁面,注意設定Header,標誌讓瀏覽器以html方式處理。

        PrintWriter pw =null;
        response.setHeader("Content-Type","text/html;charset=UTF-8");
        try {
            pw = response.getWriter();
            pw.write(sbHtml.toString());
            pw.flush();
        } 
catch (IOException e) { e.printStackTrace(); } finally { pw.close(); }

2.實現方式二

1.設定springMVC實現,設定produces 標誌瀏覽器處理型別。預設是json

    @RequestMapping(value = "/getPage1", produces = {MediaType.TEXT_HTML_VALUE})
    @ResponseBody
    public String getPage1(){
        StringBuffer sbHtml 
= new StringBuffer(); sbHtml.append("<!doctype html><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"); sbHtml.append("<title>支付寶即時到賬交易介面</title></head><body>77312534</body></html>"); return
sbHtml.toString(); }

2.在做返回json轉化時,字串預設會加上雙引號,瀏覽器無法解析。需在spring-mvc.xml中做一下設定:

    <!--    增加配置,controller返回字串去掉雙引號-->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
        </mvc:message-converters>
    </mvc:annotation-driven>

補充:

java後臺操作html字串並當作一個頁面返回給瀏覽器

引入依賴包

<dependency>
        <groupId>org.jsoup</groupId>
        <artifactId>jsoup</artifactId>
        <version>1.10.3</version>
    </dependency>

後臺程式碼如下

/**
     * 操作html字串
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("WStoHtml")
    public void WStoHtml(HttpServletRequest request,HttpServletResponse response) throws IOException{
        String url = "http://localhost:8082/bim/static/form2/ApplicationFormTable.htm";
        String body = HttpClientUtil.doPost(url);//body為獲取的html程式碼
        //System.out.println(body);
        //System.out.println("11111");
        Document doc = Jsoup.parse(body);
        Elements es =  doc.select("table");
        for (Element element : es) {
            element.html("123");//將table的內容替換為123
        }
        for (Element element : es) {
            System.out.println(element.html());
        }
        System.out.println(doc.outerHtml());
        response.setContentType("text/html;charset=utf-8"); 
        PrintWriter out=response.getWriter();
        out.println(doc.outerHtml());
    }