paint-brush
UNikeza Njani iServer-Cala ngeSpring Bootnge@nfrankel
323 ukufunda
323 ukufunda

UNikeza Njani iServer-Cala ngeSpring Boot

nge Nicolas Fränkel8m2024/09/22
Read on Terminal Reader

Inde kakhulu; Ukufunda

I-WebJars yitekhnoloji eyilwe nguJames Ward ukusingatha ezi mfuno zichanekileyo. IiWebJars ngamathala eencwadi ewebhu kwicala lomxhasi (umzekelo. jQuery & Bootstrap) zipakishwe kwiifayile zeJAR (Java Archive). I-Vaadin, kunye ne-paradigm yayo ekhethekileyo, ivelele ngokwenene phakathi kweendlela.
featured image - UNikeza Njani iServer-Cala ngeSpring Boot
Nicolas Fränkel HackerNoon profile picture

Ukuqonda amanyathelo okwabelwana ngawo ekusekweni kweprojekthi kubalulekile ngaphambi kokuphonononga kwiinkcukacha zetekhnoloji yokwandisa umxhasi ngamnye. Iimfuno zam kwisithuba sokugqibela bezicace gca:


  • Ndiza kuthatha imbono yomphuhlisi we-backend
  • Akukho nyathelo lokwakha langaphambili: akukho TypeScript, akukho minification, njl.
  • Zonke izinto ezixhomekeke zilawulwa kwi-backend app, okt , Maven


Kubalulekile ukuqaphela ukuba itekhnoloji endiza kuyichaza, ngaphandle kweVaadin, ilandela indlela efanayo. I-Vaadin, kunye ne-paradigm yayo ekhethekileyo, ivelele ngokwenene phakathi kweendlela.

WebJars

I-WebJars yiteknoloji eyenzelwe ngo-2012 nguJames Ward ukusingatha ezi mfuno zichanekileyo.


IiWebJars ngamathala eencwadi ewebhu kwicala lomxhasi (umzekelo ijQuery & Bootstrap) zipakishwe kwiifayile zeJAR (Java Archive).


  • Ngokucacileyo kwaye kulula ukulawula ukuxhomekeka kwecala lomxhasi kwizicelo zewebhu ezisekelwe kwi-JVM
  • Sebenzisa izixhobo zokwakha ezisekwe kwi-JVM (umzekelo, iMaven, iGradle, i-sbt, ...) ukukhuphela ukuxhomekeka kwabaxhasi bakho.
  • Yazi ukuba ngabaphi abaxhomekeke kwicala lomxhasi oyisebenzisayo
  • Ukuxhomekeka okuguqukayo kusonjululwa ngokuzenzekelayo kwaye ngokuzithandela kulayishwe nge-RequireJS
  • Isasazwe eMaven Central
  • I-CDN kawonkewonke, inikwe ngesisa nguJSDelivr


-- Iwebhusayithi yeWebjars


I-WebJar yi-JAR eqhelekileyo equlethe i-asethi yewebhu. Ukongeza iWebJar kuxhomekeke kwiprojekthi akukho nto ithile:


 <dependencies> <dependency> <groupId>org.webjars.npm</groupId> <artifactId>alpinejs</artifactId> <version>3.14.1</version> </dependency> </dependencies>


Uxanduva lwesakhelo kukuveza ii-asethi phantsi kwe-URL. Umzekelo, iSpring Boot iyenza kwiklasi WebMvcAutoConfiguration :


 public void addResourceHandlers(ResourceHandlerRegistry registry) { if (!this.resourceProperties.isAddMappings()) { logger.debug("Default resource handling disabled"); return; } addResourceHandler(registry, this.mvcProperties.getWebjarsPathPattern(), //1 "classpath:/META-INF/resources/webjars/"); addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> { registration.addResourceLocations(this.resourceProperties.getStaticLocations()); if (this.servletContext != null) { ServletContextResource resource = new ServletContextResource(this.servletContext, SERVLET_LOCATION); registration.addResourceLocations(resource); } }); }
  1. Okwendalo yi "/webjars/**"


Ngaphakathi kweJAR, unokufikelela kwii-asethi ngendlela yazo kunye negama. Ulwakhiwo ekuvunyelwene ngalo kukugcina ii-asethi ngaphakathi resources/webjars/<library>/<version> . Nalu ulwakhiwo lwe alpinejs-3.14.1.jar :


 META-INF |_ MANIFEST.MF |_ maven.org.webjars.npm.alpinejs |_ resources.webjars.alpinejs.3.14.1 |_ builds |_ dist |_ cdn.js |_ cdn.min.js |_ src |_ package.json


Ngaphakathi kweSpring Boot, unokufikelela kuguqulelo olungancitshiswanga nge /webjars/alpinejs/3.14.1/dist/cdn.js /dist/cdn.js .


Abaphuhlisi bakhupha amathala eencwadi asecaleni kwabathengi rhoqo. Xa utshintsha inguqulelo yokuxhomekeka kwi-POM, kufuneka utshintshe umendo wesiphelo sangaphambili, mhlawumbi kwiindawo ezininzi. Iyadika, ayinaxabiso elongezelelweyo, kwaye usengozini yokuphoswa lutshintsho.


Iprojekthi ye-WebJars Locator ijolise ekuphepheni yonke le miba ngokubonelela ngendlela engenanguqulelo, oko kukuthi , /webjars/alpinejs/dist/cdn.js . Unokufezekisa oku ngokongeza i webjars-locator JAR kuxhomekeke kuwe:


 <dependencies> <dependency> <groupId>org.webjars.npm</groupId> <artifactId>alpinejs</artifactId> <version>3.14.1</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>webjars-locator</artifactId> <version>0.52</version> </dependency> </dependencies>


Ndiza kusebenzisa le ndlela kuyo yonke itekhnoloji yangaphambili. Ndiza kongeza ilayibrari ye-Bootstrap CSS ukubonelela ngojongano olungcono lomsebenzisi.

I-Thymeleaf

I-Thymeleaf yitekhnoloji yonikezelo lwe-server-side.


I-Thymeleaf yinjini yetemplate ye-Java ye-server yanamhlanje kuzo zombini iwebhu kunye neemeko ezizimeleyo.


Eyona njongo iphambili ye-Thymeleaf kukuzisa iitemplates zendalo ezintle kuphuhliso lwakho lokuqhutywa komsebenzi — i-HTML enokuthi iboniswe ngokuchanekileyo kwizikhangeli kwaye iphinde isebenze njengeprototypes engatshintshiyo, ivumela intsebenziswano eyomeleleyo kumaqela ophuhliso.


Ngeemodyuli zeSakhelo seSpring, inkitha yokudibanisa kunye nezixhobo zakho ozithandayo, kunye nokukwazi ukuplaga ekusebenzeni kwakho, i-Thymeleaf ilungele uphuhliso lwewebhu lwe-HTML5 JVM yanamhlanje - nangona kuninzi enokukwenza.


-- Thymeleaf


Ndandisengumcebisi ukuqala kwam ukufunda nge-Thymeleaf. Ngelo xesha, amaPhepha eSeva yeJava ayesekupheleni kobomi babo. Ubuso beseva yeJava bezizama ukuzibuyisela; I-IMHO, abaphumelelanga.


Ndacinga ukuba i-Thymeleaf yayiyindlela emangalisayo: ikuvumela ukuba ubone iziphumo kwindawo engatshintshiyo ngexesha loyilo kunye nomncedisi ngexesha lophuhliso. Ngcono nangakumbi, ungahamba ngaphandle komthungo phakathi kwenye nenye usebenzisa ifayile efanayo. Andizange ndisibone esi sixhobo sisetyenziswa.


Nangona kunjalo, i-Spring Boot ixhasa ngokupheleleyo i-Thymeleaf. I-icing kwikhekhe: i-icing yokugqibela ifumaneka nge-HTML namespace kwiphepha. Ukuba awuzange uthenge kwi-JSF (umtshabalalisi: khange ndiyenze), i-Thymeleaf lulwimi lwanamhlanje lokuyilwa kwi-SSR.


Nantsi isampuli yedemo evela kwiwebhusayithi:


 <table> <thead> <tr> <th th:text="#{msgs.headers.name}">Name</th> <th th:text="#{msgs.headers.price}">Price</th> </tr> </thead> <tbody> <tr th:each="prod: ${allProducts}"> <td th:text="${prod.name}">Oranges</td> <td th:text="${#numbers.formatDecimal(prod.price, 1, 2)}">0.99</td> </tr> </tbody> </table>


Nantsi i-Thymeleaf 101, ukuba ufuna ukuziqhelanisa neteknoloji.


  • Xa uvula ifayile ye-HTML, isiphequluli sibonisa ixabiso eliqhelekileyo ngaphakathi kweethegi, oko kukuthi , Name kunye Price . Xa uyisebenzisa kumncedisi, i-Thymeleaf iyakhaba kwaye inike ixabiso elibalwe ukusuka ku th:text , #{msgs.headers.name} kunye #{msgs.headers.price} .
  • Umsebenzisi we- $ ubuza ngembotyi yaseNtwasahlobo ekwalelo gama ligqithiselweyo kwimodeli. ${prod.name} ilingana ne model.getBean("prod").getName()" .
  • I # ibiza umsebenzi.
  • th:each ivumela iilophu.

Ukudityaniswa kwe-Thymeleaf kunye neNkqubo-sikhokelo yesiphelo sangaphambili

Uninzi, ukuba alukho zonke, izikhokelo zesiphelo sangaphambili zisebenza ngemodeli yecala lomxhasi. Kufuneka sidibanise phakathi kwemodeli yecala lomncedisi kunye necala lomthengi.


Ikhowudi yecala leseva endiyisebenzisayo yile ilandelayo:


 data class Todo(val id: Int, var label: String, var completed: Boolean = false) //1 fun config() = beans { bean { mutableListOf( //2 Todo(1, "Go to the groceries", false), Todo(2, "Walk the dog", false), Todo(3, "Take out the trash", false) ) } bean { router { GET("/") { ok().render( //3 "index", //4 mapOf("title" to "My Title", "todos" to ref<List<Todo>>()) //5 ) } } } }
  1. Chaza iklasi Todo .


  2. Yongeza uluhlu lwenkumbulo kumzi-mveliso weembotyi. Kwi-app eqhelekileyo, uya kusebenzisa Repository ukufunda kwisiseko sedatha.


  3. Nikela itemplate yeHTML.


  4. Ithempleyithi ithi src/main/resources/templates/index.html eneempawu ze-Thymeleaf.


  5. Beka imodeli kumxholo wephepha.



I-Thymeleaf inikezela nge- th:inline="javascript" uphawu kwi <script> ithegi. Inika idatha yecala leseva njengeenguqu zeJavaScript. Amaxwebhu achaza ngcono kakhulu kunokuba bendinokwenza:


Into yokuqala esinokuyenza ngokufakwa kweskripthi kukubhala ixabiso lamazwi kwizikripthi zethu, njengale:


 <script th:inline="javascript"> /*<![CDATA[*/ ... var username = /*[[${session.user.name}]]*/ 'Sebastian'; ... /*]]>*/ </script>


I /*[[...]]*/ isintaksi, iyalela i-Thymeleaf ukuba ivavanye intetho equlethweyo. Kodwa kukho iimpembelelo ezingakumbi apha:


  • Ukuba luluvo lwejavascript (/*...*/) , intetho yethu ayisayi kuhoywa xa ubonisa iphepha ngokwestatically kwisikhangeli.

  • Ikhowudi emva kwentetho engaphakathi kumgca ( 'Sebastian' ) iya kuphunyezwa xa kuboniswa iphepha ngokwezibalo.

  • I-Thymeleaf izakwenza intetho kwaye ifake isiphumo, kodwa iyakususa yonke ikhowudi emgceni emva kokuchazwa kwe-inline ngokwayo (inxalenye eyenziwayo xa iboniswe ngokwezibalo).


-- Amaxwebhu e-Thymeleaf


Ukuba sisebenzisa oku kungasentla kwikhowudi yethu, sinokufumana iimpawu zemodeli ezigqithiswe nguSpring njenge:


 <script th:inline="javascript"> /*<![CDATA[*/ window.title = /*[[${title}]]*/ 'A Title' window.todos = /*[[${todos}]]*/ [{ 'id': 1, 'label': 'Take out the trash', 'completed': false }] /*]]>*/ </script>


Xa inikezelwe kwicala leseva, isiphumo sithi:


 <script> /*<![CDATA[*/ window.title = "My title"; window.todos: [{"id":1,"label":"Go to the groceries","completed":false},{"id":2,"label":"Walk the dog","completed":false},{"id":3,"label":"Take out the trash","completed":false}] /*]]>*/ </script>

Isishwankathelo

Kule post, ndichaze izinto ezimbini endiza kuzisebenzisa kulo lonke olu luhlu:


  • I-WebJars ilawula ukuxhomekeka kwicala lomxhasi kwi-Maven POM yakho.


  • I-Thymeleaf yindlela yokuyila edibanisa kakuhle ne-Spring Boot.


Ikhowudi yemvelaphi epheleleyo yesi sithuba inokufumaneka kwi-GitHub.


Hamba uqhubeke:


Yapapashwa okokuqala kwi -A Java Geek ngoSeptemba 15, 2024

L O A D I N G
. . . comments & more!

About Author

Nicolas Fränkel HackerNoon profile picture
Nicolas Fränkel@nfrankel
Developer Advocate for Apache APISIX *** Learner *** Author of http://leanpub.com/integrationtest

ZIJONGE IIMPAWU

ELI NQAKU LINIKEZELWE KU...