Spring MVC(二)—— 集成handlebars插件

 

本篇介绍引入spring mvc框架中引入handlebars.js插件最基本步骤

 1、下载handlebars.js插件,并添加到项目中

2、下载handlebars依赖的jar包,添加到工程

  红框中的是handlebars核心包,其他是handlebars依赖的工具包

3、在spring mvc配置文件springMvc-servlet.xml中添加handlebars视图解析器配置

 1 <!-- VIEW RESOLVER -->
 2     <bean id="handlebarsViewResolver" class="com.github.jknack.handlebars.springmvc.HandlebarsViewResolver">
 3         <!--  <constructor-arg value="com.ruijie.crazy.handlebars.CustomHandlebarsView" />-->
 4         <property name="order" value="1" />
 5         <property name="prefix" value="/page/" />
 6         <property name="suffix" value=".html" />
 7         <property name="contentType" value="text/html;charset=utf-8" />
 8         <property name="failOnMissingFile" value="false" />
 9         <property name="cache" value="false" />
10     </bean>

4、测试

controller中实现如下:

 1 package com.ruijie.crazy.controller;
 2 
 3 import java.util.HashMap;
 4 import java.util.Map;
 5 
 6 import org.springframework.stereotype.Controller;
 7 import org.springframework.web.bind.annotation.RequestMapping;
 8 import org.springframework.web.bind.annotation.RequestMethod;
 9 import org.springframework.web.bind.annotation.ResponseBody;
10 import org.springframework.web.servlet.ModelAndView;
11 
12 @Controller
13 @RequestMapping("/myweb")
14 public class MyFirstController {
15 
16     @RequestMapping(value = "/test", method = RequestMethod.GET)
17     public ModelAndView getUserInfoByCode() {  
18         Map<String, Object> map = new HashMap<String, Object>();  
19         map.put("userName", "ypf");  
20         return new ModelAndView("hello",map);
21     }
22         
23 }

前端hello.html实现如下:

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html>
 3 <head>
 4     <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 5     <meta http-equiv="X-UA-Compatible" content="IE=edge">
 6     <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">  
 7     <title>hello ypf</title>
 8     <script type="text/javascript" src="../js/libs/jquery/jquery.min.js"></script>    
 9     <script type="text/javascript" src="../js/libs/handlebars/handlebars-1.0.0.beta.6.js"></script>
10 </head>
11 <body>
12     <div>
13         {{userName}}
14     </div>    
15 </body>
16 </html>

运行工程,在浏览器输入http://127.0.0.1/crazypf/myweb/test.html,显示结果如下:

至此handlebars成功引入工程

原文地址:https://www.cnblogs.com/ypf1989/p/5534674.html