前后端分离-代替jsp的域取值的方法
使用Thymeleaf模板,简单记录一下,有时间再总结
1.配置
<!-- thymeleaf配置开始 --> <bean id="viewResolver" class="org.thymeleaf.spring4.view.ThymeleafViewResolver"> <property name="characterEncoding" value="UTF-8"/> <property name="templateEngine" ref="templateEngine"/> </bean> <!-- 模板引擎 --> <bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine"> <property name="templateResolver" ref="templateResolver"/> </bean> <!-- 模板解析器 --> <bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver"> <constructor-arg ref="servletContext"/> <property name="prefix" value="/pages/"/> <property name="suffix" value=".html"/> <property name="templateMode" value="HTML5"/> <property name="cacheable" value="false"/> <property name="characterEncoding" value="UTF-8"/> </bean> <!-- thymeleaf配置结束 -->
2、html中加入标签
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
3、controller方法
@ResponseBody @RequestMapping(value = "/login",method = RequestMethod.POST) public ModelAndView login(String account,HttpSession session)throws Exception{ ModelAndView mv = new ModelAndView(); Admin admin = adminService.findByAdminAccount(account); // mv.addObject("admin",admin); mv.setViewName("back_admin_main"); session.setAttribute("admin",admin); return mv; }
4.前端取值的方法
<input type="text" class="form-control" placeholder="地址" id="address" required="true" th:value="${admin.number}">
5.注意
前端取值可能会有红色波浪线提醒错误,没关系,能取到即可,可以自行百度取消模板警告