溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

使用Springboot怎么對Freemarker進行整合

發布時間:2020-12-21 14:49:17 來源:億速云 閱讀:191 作者:Leah 欄目:開發技術

這篇文章將為大家詳細講解有關使用Springboot怎么對Freemarker進行整合,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。

1、導入依賴

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

2、準備一個Freemarker模板(.ftl)

使用Springboot怎么對Freemarker進行整合

3、注入Configuration對象(freemarker.template包下)

使用Springboot怎么對Freemarker進行整合

4、生成商品詳情模板

@Controller
@RequestMapping("/goodItem")
public class GoodItemController {
  @Reference
  private IGoodsService goodsService;

  @Autowired
  private Configuration configuration;

  @RequestMapping("/createHtml")
  @ResponseBody
  public String createHtml(int gid, HttpServletRequest request){
    //通過商品id獲取商品詳情信息
    Goods goods = goodsService.queryById(gid);
    String [] images=goods.getGimage().split("\\|");
    //通過模板生成商品靜態頁面
    try {
      //獲取商品詳情的模板對象
      Template template = configuration.getTemplate("goodsItem.ftl");
      //準備商品數據
      Map<String,Object> map=new HashMap<>();
      map.put("goods",goods);
      map.put("context",request.getContextPath());
      //freemarker頁面沒有分割功能,所以通過后臺將圖片分割后,將圖片數組傳到后臺
      map.put("images",images);
      //生成靜態頁
      //獲得classpath路徑
      //靜態頁面的名稱必須和商品有所關聯,最簡單的方式就是用商品的id作為頁面的名字
      String path = this.getClass().getResource("/static/page/").getPath()+goods.getId()+".html";;
      template.process(map,new FileWriter(path));
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "";
  }
}

注意:
1、freemarker頁面不能通過<base th:href="${#request.getContextPath()+'/'}" rel="external nofollow" >獲得項目的根路徑。
因此可從后臺將根路徑傳到前端,然后通過<base href="${context}/" rel="external nofollow" />獲取。
2、當page是一個空文件夾的時候,會報錯。這是因為maven項目不會對空文件夾進行打包編譯。

FreeMarker的基本語法

使用Springboot怎么對Freemarker進行整合

使用Springboot怎么對Freemarker進行整合

關于使用Springboot怎么對Freemarker進行整合就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女