首页 > 解决方案 > FreeMarker 和 HTML

问题描述

我正在尝试使用FreeMarker模板,这是我的代码:

@GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("{queue}")
    public String test(@PathParam("queue") String qy,
    @Context HttpServletRequest request) {

        Map<String,Object> model = new HashMap<String,Object>();

         String listTemplate = "<HTML><HEAD><STYLE>${css}</STYLE></HEAD><BODY><UL> the queue includes : ${queues}</UL></BODY></HTML>";

String listCss = inMemService.getWebCss("list");
        model.put("css", listCss);

         String result = null ; 
        IQueue queue = com.myproject.hc.Main.getHzInstance().getQueue(qy);

        // Build the data-model

                    Object[] array = queue.toArray();
                int size = queue.size();
                int i; 
               for (i = 0; i < size ; i ++) {

                   temp = temp + " " + array [i] + " ";
               }


            model.put("queues", temp);

             Template template ;
            try {
                template = new Template("process", new StringReader(
                        listTemplate), new Configuration());
                Writer stringWriter = new StringWriter();
                template.process(model, stringWriter);
                stringWriter.flush();
                result = stringWriter.toString();
            } catch (IOException e) {

            } catch (TemplateException e) {

            } 

            return result;
    }

但是,当我添加到队列中并转到 时@Path,我得到以下输出,它不能识别为HTML

<HTML><HEAD><STYLE>body {background-color: lightgrey;} h1 {color: black;text-align: left;} p {font-family: verdana;font-size: 20px;}</STYLE></HEAD><BODY><UL> the queue includes :  LA  NYC </UL></BODY></HTML>

标签: javafreemarker

解决方案


您的 HTML 很好,您需要在返回 HTML(而不是 JSON)的代码中声明。

您应该将@Produces(MediaType.APPLICATION_JSON)替换为:

@Produces({MediaType.TEXT_HTML})

@Produces 注释用于指定资源可以生成并发送回客户端的 MIME 媒体类型或表示。


推荐阅读