Today we have to create product catalogue:-
- Open Eclipse -> File -> Spring starter project -> (make sure Type: Maven and Packaging:Jar
then Next;-
Add dependencies:
- Template Engine in Thymeleaf
- Web in Spring web , then finish
what is Template Engine?
A Template Engine is software used to combine Java data (Java objects) with HTML templates to produce formatted output —> generating dynamically rendered web pages
Java objects → Backend data
HTML templates → Frontend design
Formatted output → Clean HTML response
Dynamically rendered → Data changes based on user input or back end data.
#### rendered mean?
- Rendering mean converting back-end data into a format (HTML/JSON) then you visually show your the result.
dynamically rendered mean?
Displaying to the changing data(not fixed) on a web page based on the user's action or back end data or back end update.
Example:-
static render = shows same content every time.
sample.html
<h1>Welcome to Pizza Shop</h1> // Always same text
Dynamic render => Content change based on java data.
sample.html
<h1 th:text="${userName}"></h1> // Shows "Welcome, Prasanth" if userName = Prasanth
<tr th:each="pizza : ${pizzaList}">
<td th:text="${pizza.name}"></td>
<td th:text="${pizza.price}"></td>
</tr>
- if your java sends a list of pizzas ,this table will automatically render dynamically based on that list.
## Why to use Template Engine?
1.To render dynamic content in html using back end data(You get data from your Java code (Controller/Service)
And display that data in your HTML using a template engine).
2.Avoid manually writing long string(String concatenation(unclean and hard to maintain)) based HTML in java.
without template engine(manual way)
String html = "<p>" + user.getName() + "</p>";
// Not readable, difficult to change later ,very Hard to read or not maintainable.
3.keep code (java) and view (HTML) separate for easy to maintain
Template Engines:-
- Thymeleaf:mostly used to spring boot
used to create dynamic web page.
It works in both web (running inside web server like tomcat)and non-web environments(running background or offline java app like without web server)
.JSP(JavaServer Pages):Old template engine, used with Servlet(Java class(Handling requests/responses)like old Controller) & spring Mvc,not recommeded for new projects
.JSTL is commonly used with JSP pages for dynamic content rendering,As of now used Thymeleaf.
FreeMarker:
supported in spring boot,suitable for emails or pages,java web apps(Frontend+BackEnd+Database).
Mustache: usde Java,Spring Boot & javascript.
Spring web:-
- spring Web is a module(tool) spring framework ,that spring web allow to you build web application,REST APIs(@RestController) ,web pages(@controller),Handel Http request(@GetMapping,@PostMapping,@PutMapping,@PatchMapping,@DeleteMapping,@RequestMapping),supports spring MVC architecture.
Note:we will see another blog for only Annotation for what,why,where,when..Coming to Soon.
step2:
- After finished create class Products(pojo class)
step3:
inside class create private variables
private String name,description,url;
private int price;
then, select those variable, Right click mouse -> sourec -> generate getter and setter method.
This Products is pojo class like modal(data) this class filed of backend Db Columns.controller just request mapper , Pojo class provide the actual data, in this project, actual database is give data. now we see how to get the data from pojo class not to a database.
Pojo class mean -> Plain old java object that mean Project class object created in controller class p1 ,p2,p3 this java object ,this object need values insitailiation to constructor ,this constructor need to getter(view the value) and setter(set/change the value) in the Pojo class.why we create object in controller class because all the data sent into with help controller class to view the data .
step4:
- We want tor handle web application request mapping and return to HTML view page.so i will use @Controller
- Create class ProductsController.then we create the @GetMapping("/products_list") is a Spring annotation used to map HTTP GET requests to specific handler methods within a controller,then create the method like
- public String show_products(),then add 3 objects p1,p2,p3,now came error,so you go generate the constructor for fields same as before done getter and setter for ,source =>generate constructor for fields.
step:5
- If you want to share multiple objects (like multiple Products) from backed to front end use List or ArrayList.
- ArrayList class implement LIst inteface , ArrayList stores elements in index-based order (0, 1, 2...) if want Later change LINkdedList class instead of Arraylist class that why we use List ,it called like flexbility.
List<Products> productList = new ArrayList<Products>();
- if you want change future change anther class for flexibility(like easily to switch) that why use List.
List<Products> productList = new LinkedList<>();
productList.add(p1);
productList.add(p2);
productList.add(p3);
step:6 we gives Model interface in argument.
public String show_products(Model model)
- Model is an interface.It is used to pass all object values like data (like p1, p2, p3) inside a list(productList) from the controller to the frontend HTML (view) to display.
model.addAttribute("productList", productList);
- Now the HTML file(products.html) can access productList.
step:7
src/mani/resource/template path create products.html
add html code.
step:8
- Right click your project ,Run as application then paste url http://localhost:8080/products_list
scenario:
pojo/Model (data)=> sends data to Controller => controller adds data to Model => returns to View (HTML) => HTML shows the data.
Pojoclass
package com.example.demo;
public class Products {
private String name,description,url;
private int price;
public Products(String name, String description, String url, int price) {
super();
this.name = name;
this.description = description;
this.url = url;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
Example
@Controller
public class ProductsController {
@GetMapping("/products_list")
public String show_products(Model model)
{
Products p1 = new Products ("Apple","phone","https://encrypted-tbn0.gstatic.com/shopping?q=tbn:ANd9GcS0CHFYxZH8wkjNb98zrWayFHoffcMoZSdxpRfMpc2UB9MPj0seoKo5lZqWiFXYhBFMjMl_kFAzmq5iadxmy30qNBOUDs53Az78RmpzT5Da",145000);
Products p2 = new Products ("Apple","phone","https://encrypted-tbn0.gstatic.com/shopping?q=tbn:ANd9GcS0CHFYxZH8wkjNb98zrWayFHoffcMoZSdxpRfMpc2UB9MPj0seoKo5lZqWiFXYhBFMjMl_kFAzmq5iadxmy30qNBOUDs53Az78RmpzT5Da",145000);
Products p3 = new Products ("Apple","phone","https://encrypted-tbn0.gstatic.com/shopping?q=tbn:ANd9GcS0CHFYxZH8wkjNb98zrWayFHoffcMoZSdxpRfMpc2UB9MPj0seoKo5lZqWiFXYhBFMjMl_kFAzmq5iadxmy30qNBOUDs53Az78RmpzT5Da",145000);
List<Products> productList = new ArrayList<Products>();
productList.add(p1);
productList.add(p2);
productList.add(p3);
model.addAttribute("productList", productList);
return "products";
}
}
Example:-
products.html
<!DOCTYPE html>
<!-- ctr+shift+/ -->
<!-- not comlsery i said thymeleaf template used thats all
-->
<html xmlns:th="http://www.thymeleaf.org/">
<head>
<title>Products List</title>
<style type="text/css">
img {
width: 200px;
height: auto;
}
</style>
</head>
<body>
<h1>Product List</h1>
<!-- for loop to used thymleaf,$ mean to go to contreller class to get data products list tp display the division
img image src is as source
-->
<div th:each ="products : ${productList}">
<img th:src="${products.url}">
<h2 th:text="${products.name}" ></h2>
<h2 th:text="${products.description}" ></h2>
<h2 th:text="${products.price}" ></h2>
</div>
</body>
</html>
Top comments (0)