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());
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM