javascript
Thymeleaf与Spring集成(第1部分)
1.引言
本文重點(diǎn)介紹如何將Thymeleaf與Spring框架集成。 這將使我們的MVC Web應(yīng)用程序能夠利用Thymeleaf HTML5模板引擎,而不會(huì)丟失任何Spring功能。 數(shù)據(jù)層使用Spring Data與mongoDB數(shù)據(jù)庫(kù)進(jìn)行交互。
該示例包含在酒店的單頁(yè)Web應(yīng)用程序中,從中我們可以發(fā)送兩個(gè)不同的請(qǐng)求:
- 插入一個(gè)新來(lái)賓:一個(gè)同步請(qǐng)求,顯示Thymeleaf如何與Spring的表單支持bean集成在一起。
- 列出來(lái)賓:異步請(qǐng)求,顯示如何使用AJAX處理片段渲染。
本教程希望您了解Thymeleaf的基礎(chǔ)知識(shí)。 如果不是,則應(yīng)首先閱讀本文 。
這是應(yīng)用程序流程的示例:
本示例基于Thymeleaf 2.1和Spring 4版本。
- 源代碼可以在github上找到。
2.配置
本教程采用JavaConfig方法來(lái)配置所需的bean。 這意味著不再需要xml配置文件。
web.xml
由于我們要使用JavaConfig,因此需要指定AnnotationConfigWebApplicationContext作為將配置Spring容器的類(lèi)。 如果不指定,默認(rèn)情況下它將使用XmlWebApplicationContext 。
在定義配置文件的位置時(shí),我們可以指定類(lèi)或包。 在這里,我要說(shuō)明我的配置類(lèi)。
<!-- Bootstrap the root context --> <listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener><!-- Configure ContextLoaderListener to use AnnotationConfigWebApplicationContext --> <context-param><param-name>contextClass</param-name><param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value> </context-param><!-- @Configuration classes or package --> <context-param><param-name>contextConfigLocation</param-name><param-value>xpadro.thymeleaf.configuration.WebAppConfiguration</param-value> </context-param><!-- Spring servlet --> <servlet><servlet-name>springServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextClass</param-name><param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value></init-param> </servlet> <servlet-mapping><servlet-name>springServlet</servlet-name><url-pattern>/spring/*</url-pattern> </servlet-mapping>彈簧配置
我的配置分為兩類(lèi):百里香葉彈簧集成( WebAppConfiguration類(lèi))和mongoDB配置( MongoDBConfiguration類(lèi))。
WebAppConfiguration.java
@EnableWebMvc @Configuration @ComponentScan("xpadro.thymeleaf") @Import(MongoDBConfiguration.class) public class WebAppConfiguration extends WebMvcConfigurerAdapter {@Bean@Description("Thymeleaf template resolver serving HTML 5")public ServletContextTemplateResolver templateResolver() {ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();templateResolver.setPrefix("/WEB-INF/html/");templateResolver.setSuffix(".html");templateResolver.setTemplateMode("HTML5");return templateResolver;}@Bean@Description("Thymeleaf template engine with Spring integration")public SpringTemplateEngine templateEngine() {SpringTemplateEngine templateEngine = new SpringTemplateEngine();templateEngine.setTemplateResolver(templateResolver());return templateEngine;}@Bean@Description("Thymeleaf view resolver")public ThymeleafViewResolver viewResolver() {ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();viewResolver.setTemplateEngine(templateEngine());return viewResolver;}@Bean@Description("Spring message resolver")public ResourceBundleMessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("i18n/messages"); return messageSource; }@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/");} }通過(guò)查看上面的代碼可以突出顯示以下內(nèi)容:
- @EnableWebMvc :這將啟用Spring MVC注釋,例如@RequestMapping。 這將與xml名稱(chēng)空間<mvc:annotation-driven />相同
- @ComponentScan(“ xpadro.thymeleaf”) :激活xpadro.thymeleaf程序包和子程序包中的組件掃描。 用@Component和相關(guān)注釋注釋的類(lèi)將被注冊(cè)為bean。
- 我們正在注冊(cè)三個(gè)bean,它們是配置Thymeleaf并將其與Spring框架集成所必需的。
- 模板解析器:解析模板名稱(chēng)并將其委托給servlet上下文資源解析器。
MongoDBConfiguration.java
@Configuration @EnableMongoRepositories("xpadro.thymeleaf.repository") public class MongoDBConfiguration extends AbstractMongoConfiguration {@Overrideprotected String getDatabaseName() {return "hotel-db";}@Overridepublic Mongo mongo() throws Exception {return new Mongo();} }此類(lèi)擴(kuò)展了AbstracMongoConfiguration ,它定義了mongoFactory和mongoTemplate bean。
@EnableMongoRepositories將掃描指定的包,以查找擴(kuò)展MongoRepository的接口。 然后,它將為每個(gè)容器創(chuàng)建一個(gè)bean。 稍后,我們將在數(shù)據(jù)訪(fǎng)問(wèn)層部分看到這一點(diǎn)。
3.Thymeleaf – Spring MVC集成
酒店控制器
控制器負(fù)責(zé)訪(fǎng)問(wèn)服務(wù)層,根據(jù)結(jié)果構(gòu)造視圖模型并返回視圖。 使用我們?cè)谏弦还?jié)中設(shè)置的配置,現(xiàn)在MVC控制器將能夠返回將被解析為T(mén)hymeleaf視圖的視圖ID。
在下面,我們可以看到控制器處理初始請(qǐng)求的片段(http:// localhost:8080 / th-spring-integration / spring / home):
@Controller public class HotelController {@Autowiredprivate HotelService hotelService;@ModelAttribute("guest")public Guest prepareGuestModel() {return new Guest();}@ModelAttribute("hotelData")public HotelData prepareHotelDataModel() {return hotelService.getHotelData();}@RequestMapping(value = "/home", method = RequestMethod.GET)public String showHome(Model model) {prepareHotelDataModel();prepareGuestModel();return "home";}... }典型的MVC控制器返回一個(gè)“主”視圖ID。 Thymeleaf模板解析器將在/ WEB-INF / html /文件夾中查找名為“ home.html”的模板,如配置中所示。 此外,名為“ hotelData”的視圖屬性將向Thymeleaf視圖公開(kāi),其中包含需要在初始視圖上顯示的酒店信息。
主頁(yè)視圖的此片段顯示了如何使用Spring表達(dá)式語(yǔ)言(Spring EL)訪(fǎng)問(wèn)view屬性的某些屬性:
<span th:text="${hotelData.name}">Hotel name</span><br /> <span th:text="${hotelData.address}">Hotel address</span><br />Thymeleaf的另一個(gè)不錯(cuò)的功能是,它可以解析通過(guò)MessageSource接口配置的Spring托管消息屬性。
<h3 th:text="#{hotel.information}">Hotel Information</h3>錯(cuò)誤處理
如果已經(jīng)存在具有相同ID的用戶(hù),則嘗試添加新用戶(hù)將引發(fā)異常。 將處理異常,并使用錯(cuò)誤消息呈現(xiàn)主視圖。
由于我們只有一個(gè)控制器,因此無(wú)需使用@ControllerAdvice 。 我們將改為使用@ExceptionHandler注釋的方法。 您會(huì)注意到,我們將國(guó)際化消息作為錯(cuò)誤消息返回:
@ExceptionHandler({GuestFoundException.class}) public ModelAndView handleDatabaseError(GuestFoundException e) {ModelAndView modelAndView = new ModelAndView();modelAndView.setViewName("home");modelAndView.addObject("errorMessage", "error.user.exist");modelAndView.addObject("guest", prepareGuestModel());modelAndView.addObject("hotelData", prepareHotelDataModel());return modelAndView; }Thymeleaf將使用$ {}解析view屬性,然后將解析消息#{}:
<span class="messageContainer" th:unless="${#strings.isEmpty(errorMessage)}" th:text="#{${errorMessage}}"></span>th:除非Thymeleaf屬性?xún)H在返回錯(cuò)誤消息后才呈現(xiàn)span元素。
4,服務(wù)層
服務(wù)層訪(fǎng)問(wèn)數(shù)據(jù)訪(fǎng)問(wèn)層并添加一些業(yè)務(wù)邏輯。
@Service("hotelServiceImpl") public class HotelServiceImpl implements HotelService {@AutowiredHotelRepository hotelRepository;@Overridepublic List<Guest> getGuestsList() {return hotelRepository.findAll();}@Overridepublic List<Guest> getGuestsList(String surname) {return hotelRepository.findGuestsBySurname(surname);}@Overridepublic void insertNewGuest(Guest newGuest) {if (hotelRepository.exists(newGuest.getId())) {throw new GuestFoundException();}hotelRepository.save(newGuest);} }5,數(shù)據(jù)訪(fǎng)問(wèn)層
HotelRepository擴(kuò)展了Spring Data類(lèi)MongoRepository 。
public interface HotelRepository extends MongoRepository<Guest, Long> {@Query("{ 'surname' : ?0 }")List<Guest> findGuestsBySurname(String surname); }這只是一個(gè)接口,我們不會(huì)實(shí)現(xiàn)。 如果您還記得配置類(lèi),我們添加了以下注釋:
@EnableMongoRepositories("xpadro.thymeleaf.repository")由于這是存儲(chǔ)庫(kù)所在的包,因此Spring將創(chuàng)建一個(gè)bean并向其注入mongoTemplate。 擴(kuò)展此接口可為我們提供通用的CRUD操作。 如果需要其他操作,則可以使用@Query注釋添加它們(請(qǐng)參見(jiàn)上面的代碼)。
六,結(jié)論
我們已經(jīng)配置了Thymeleaf來(lái)解析Spring托管的Web應(yīng)用程序中的視圖。 這允許視圖訪(fǎng)問(wèn)Spring Expression Language和消息解析。 本教程的下一部分將展示如何將表單鏈接到Spring表單支持bean,以及如何通過(guò)發(fā)送AJAX請(qǐng)求來(lái)重新加載片段。
翻譯自: https://www.javacodegeeks.com/2014/02/thymeleaf-integration-with-spring-part-1.html
總結(jié)
以上是生活随笔為你收集整理的Thymeleaf与Spring集成(第1部分)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 微信删除好友朋友圈点赞还有吗
- 下一篇: Thymeleaf与Spring集成(第