日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Thymeleaf与Spring集成(第1部分)

發布時間:2023/12/3 javascript 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Thymeleaf与Spring集成(第1部分) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1.引言

本文重點介紹如何將Thymeleaf與Spring框架集成。 這將使我們的MVC Web應用程序能夠利用Thymeleaf HTML5模板引擎,而不會丟失任何Spring功能。 數據層使用Spring Data與mongoDB數據庫進行交互。

該示例包含在酒店的單頁Web應用程序中,從中我們可以發送兩個不同的請求:

  • 插入一個新來賓:一個同步請求,顯示Thymeleaf如何與Spring的表單支持bean集成在一起。
  • 列出來賓:異步請求,顯示如何使用AJAX處理片段渲染。

本教程希望您了解Thymeleaf的基礎知識。 如果不是,則應首先閱讀本文 。

這是應用程序流程的示例:

本示例基于Thymeleaf 2.1和Spring 4版本。

  • 源代碼可以在github上找到。

2.配置

本教程采用JavaConfig方法來配置所需的bean。 這意味著不再需要xml配置文件。

web.xml

由于我們要使用JavaConfig,因此需要指定AnnotationConfigWebApplicationContext作為將配置Spring容器的類。 如果不指定,默認情況下它將使用XmlWebApplicationContext 。

在定義配置文件的位置時,我們可以指定類或包。 在這里,我要說明我的配置類。

<!-- 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>

彈簧配置

我的配置分為兩類:百里香葉彈簧集成( WebAppConfiguration類)和mongoDB配置( MongoDBConfiguration類)。

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/");} }

通過查看上面的代碼可以突出顯示以下內容:

  • @EnableWebMvc :這將啟用Spring MVC注釋,例如@RequestMapping。 這將與xml名稱空間<mvc:annotation-driven />相同
  • @ComponentScan(“ xpadro.thymeleaf”) :激活xpadro.thymeleaf程序包和子程序包中的組件掃描。 用@Component和相關注釋注釋的類將被注冊為bean。
  • 我們正在注冊三個bean,它們是配置Thymeleaf并將其與Spring框架集成所必需的。
    • 模板解析器:解析模板名稱并將其委托給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();} }

此類擴展了AbstracMongoConfiguration ,它定義了mongoFactory和mongoTemplate bean。

@EnableMongoRepositories將掃描指定的包,以查找擴展MongoRepository的接口。 然后,它將為每個容器創建一個bean。 稍后,我們將在數據訪問層部分看到這一點。

3.Thymeleaf – Spring MVC集成

酒店控制器

控制器負責訪問服務層,根據結果構造視圖模型并返回視圖。 使用我們在上一節中設置的配置,現在MVC控制器將能夠返回將被解析為Thymeleaf視圖的視圖ID。

在下面,我們可以看到控制器處理初始請求的片段(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控制器返回一個“主”視圖ID。 Thymeleaf模板解析器將在/ WEB-INF / html /文件夾中查找名為“ home.html”的模板,如配置中所示。 此外,名為“ hotelData”的視圖屬性將向Thymeleaf視圖公開,其中包含需要在初始視圖上顯示的酒店信息。

主頁視圖的此片段顯示了如何使用Spring表達式語言(Spring EL)訪問view屬性的某些屬性:

<span th:text="${hotelData.name}">Hotel name</span><br /> <span th:text="${hotelData.address}">Hotel address</span><br />

Thymeleaf的另一個不錯的功能是,它可以解析通過MessageSource接口配置的Spring托管消息屬性。

<h3 th:text="#{hotel.information}">Hotel Information</h3>

錯誤處理

如果已經存在具有相同ID的用戶,則嘗試添加新用戶將引發異常。 將處理異常,并使用錯誤消息呈現主視圖。

由于我們只有一個控制器,因此無需使用@ControllerAdvice 。 我們將改為使用@ExceptionHandler注釋的方法。 您會注意到,我們將國際化消息作為錯誤消息返回:

@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屬性僅在返回錯誤消息后才呈現span元素。

4,服務層

服務層訪問數據訪問層并添加一些業務邏輯。

@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,數據訪問層

HotelRepository擴展了Spring Data類MongoRepository 。

public interface HotelRepository extends MongoRepository<Guest, Long> {@Query("{ 'surname' : ?0 }")List<Guest> findGuestsBySurname(String surname); }

這只是一個接口,我們不會實現。 如果您還記得配置類,我們添加了以下注釋:

@EnableMongoRepositories("xpadro.thymeleaf.repository")

由于這是存儲庫所在的包,因此Spring將創建一個bean并向其注入mongoTemplate。 擴展此接口可為我們提供通用的CRUD操作。 如果需要其他操作,則可以使用@Query注釋添加它們(請參見上面的代碼)。

六,結論

我們已經配置了Thymeleaf來解析Spring托管的Web應用程序中的視圖。 這允許視圖訪問Spring Expression Language和消息解析。 本教程的下一部分將展示如何將表單鏈接到Spring表單支持bean,以及如何通過發送AJAX請求來重新加載片段。

參考:來自XavierPadró博客博客的JCG合作伙伴 Xavier Padro將Thymeleaf與Spring集成(第1部分) 。

翻譯自: https://www.javacodegeeks.com/2014/02/thymeleaf-integration-with-spring-part-1.html

總結

以上是生活随笔為你收集整理的Thymeleaf与Spring集成(第1部分)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。