觉得thyme leaf是一个非常优秀的模板解释引擎,比jsp要简洁很多,很是喜欢,可是现在有很多的可供借鉴的代码都是使用jsp编写的,自然而然的就想能否同时使用jsp与thymeleaf。
今天仅仅调试好配置文件如下:
<!-- thymeleaf的视图解析器 --> <!-- Thymeleaf View Resolver - implementation of Spring's ViewResolver interface --> <bean id="viewResolver" class="org.thymeleaf.spring4.view.ThymeleafViewResolver"> <property name="templateEngine" ref="templateEngine" /> <property name="characterEncoding" value="UTF-8" /> <property name="viewNames" value="html/*" /> <property name="order" value="2"/> </bean> <!-- 配置SpringMVC的视图解析器 --> <!--<bean class="org.springframework.web.servlet.view.RedirectView .InternalResourceViewResolver">--> <bean id="jspResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsps/"/> <property name="suffix" value=".jsp"/> <property name="viewNames" value="jsp/*" /> <property name="order" value="1"/> </bean> <!-- Thymeleaf Template Engine (Spring4-specific version) --> <bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine"> <property name="templateResolvers"> <set> <ref bean="templateResolver" /> </set> </property> </bean> <!-- Thymeleaf Template Resolver --> <bean id="templateResolver" class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver"> <property name="prefix" value="/WEB-INF/" /> <property name="suffix" value=".html" /> <property name="templateMode" value="HTML" /> <!--<property name="order" value="0"/>--> </bean>
控制器代码如下:
@RequestMapping(value = "testJsp") public String myJsp() { List<EmployeesEntity> emps = (List<EmployeesEntity>) employeeService.findAll(); return "jsp/test1"; //return "testmain"; } @RequestMapping(value = "testleaf") public String testleaf(Model model) { List<EmployeesEntity> emps = (List<EmployeesEntity>) employeeService.findAll(); String s = request.getAttributeNames().toString(); request.setAttribute("emps",emps); System.out.println(s); s = request.getParameter("id"); System.out.println(s); model.addAttribute("hello1","good"); model.addAttribute("hello","王顺初"); model.addAttribute("var1",2); model.addAttribute("obj","var data = \"" + JSON.toJSONString(model) + "\""); // request.setAttribute("var1",2); return "html/testmain"; //return "testmain"; }这样,jsp下的就使用jsp模板引擎,而html下的就使用thymeleaf引擎,非常方便。
如果要更加方便,就可以考虑使用扩展类控制器,如baseJspControl或者baseThymeLeafControl,然后设置不同的路径进行不同的解释,这样会更加方便。