Springboot整合Freemarker的實現(xiàn)詳細過程
基本配置、測試
1、導入依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
2、準備一個Freemarker模板(.ftl)
3、注入Configuration對象(freemarker.template包下)
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("\\|"); //通過模板生成商品靜態(tài)頁面 try { //獲取商品詳情的模板對象 Template template = configuration.getTemplate("goodsItem.ftl"); //準備商品數(shù)據(jù) Map<String,Object> map=new HashMap<>(); map.put("goods",goods); map.put("context",request.getContextPath()); //freemarker頁面沒有分割功能,所以通過后臺將圖片分割后,將圖片數(shù)組傳到后臺 map.put("images",images); //生成靜態(tài)頁 //獲得classpath路徑 //靜態(tài)頁面的名稱必須和商品有所關(guān)聯(lián),最簡單的方式就是用商品的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的基本語法
到此這篇關(guān)于Springboot整合Freemarker的實現(xiàn)詳細過程的文章就介紹到這了,更多相關(guān)Springboot整合Freemarker內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Mybatis-plus selectByMap條件查詢方式
這篇文章主要介紹了Mybatis-plus selectByMap條件查詢方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06SpringBoot webSocket實現(xiàn)發(fā)送廣播、點對點消息和Android接收
這篇文章主要介紹了SpringBoot webSocket實現(xiàn)發(fā)送廣播、點對點消息和Android接收,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-03-03Java IO流體系繼承結(jié)構(gòu)圖_動力節(jié)點Java學院整理
這篇文章主要介紹了Java IO流體系繼承結(jié)構(gòu)圖,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-05-05Java servlet 使用 PrintWriter 時的編碼與亂碼的示例代碼
本篇文章主要介紹了Java servlet 使用 PrintWriter 時的編碼與亂碼的示例代碼,探討了 PrintWriter 的缺省編碼與普通字符流的缺省編碼的差異,具有一定的參考價值,有興趣的可以了解一下2017-11-11解析ConcurrentHashMap: transfer方法源碼分析(難點)
ConcurrentHashMap是由Segment數(shù)組結(jié)構(gòu)和HashEntry數(shù)組結(jié)構(gòu)組成。Segment的結(jié)構(gòu)和HashMap類似,是一種數(shù)組和鏈表結(jié)構(gòu),今天給大家普及java面試常見問題---ConcurrentHashMap知識,一起看看吧2021-06-06Junit單元測試關(guān)于@Transactional注解引起的事務(wù)回滾問題
這篇文章主要介紹了Junit單元測試關(guān)于@Transactional注解引起的事務(wù)回滾問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08