Spring MVC An intro to Spring MVC with

  • Slides: 26
Download presentation
Spring MVC An intro to Spring MVC with template engine

Spring MVC An intro to Spring MVC with template engine

A spring application • Controllers • • • Handle the logic Receive HTTP requests

A spring application • Controllers • • • Handle the logic Receive HTTP requests Manipulate data/objects and store them (session, cookies, database…) Inject data into a view Returns the view (response) • Views • Html pages • Augmented html: special tags to insert dynamic content (the data injected from the controllers) • Model • The objects used to pass data to the view • Q: similarity with Node. js?

Request / response thymeleaf

Request / response thymeleaf

Controllers • HTTP requests are handled by a controller (ex-Servlet) • You can easily

Controllers • HTTP requests are handled by a controller (ex-Servlet) • You can easily identify these requests by the @Controller annotation @Controller public class Greeting. Controller { @Get. Mapping("/greeting") public String greeting(@Request. Param(name="somename", required=false, default. Value="World") String name, Model model) { model. add. Attribute(”username", somename); return "greeting"; MODEL- ה את נכיר היום } } VIEW- ה את נכיר היום

Controllers • @Get. Mapping : HTTP GET requests to /greeting • @Post. Mapping for

Controllers • @Get. Mapping : HTTP GET requests to /greeting • @Post. Mapping for POST requests • Equivalent to @Request. Mapping(method = Request. Method. POST) • @Get. Mapping: shortcut for @Request. Mapping(method = Request. Method. GET) • @Request. Param binds the value of the query String parameter name into the name parameter of the greeting() method. • This query String parameter is not required; if it is absent in the request, the default. Value of "World" is used.

Controller types • Controller may return a view • Response is HTML • Controller

Controller types • Controller may return a view • Response is HTML • Controller may return JSON • Response is intended for Javascript/Ajax client • Controller may forward the request to another controller • URL remains the URL of first controller, forward happens server side • Controller may redirect to another controller • Forward request sent to the browser, Twice as much traffic • Solves the “double submission” problem • Avoiding inflation of URLs: • Some controllers do the logic, then redirect to • controller that return views (and client populates the views with Ajax call) • No data can be passed directly so it is based on states! (session, cookies, application scopes, database)

Returning HTML (EJS את )זכרו view- ה לתוך נתונים של העברה מאפשר Model •

Returning HTML (EJS את )זכרו view- ה לתוך נתונים של העברה מאפשר Model • האובייקט . 1 : • לדוגמא @Controller מהלקוח הגיע - כ )לדוגמא <input type=“text” name=“somename”> ( טופס של ערך מקבל אז מוגדר לא אם . 2 דפולטיבי public class Greeting. Controller { @Get. Mapping("/greeting") public String greeting(@Request. Param(name="somename", required=false, default. Value="World") String a. Name, Model model) { model. add. Attribute(”username", a. Name); בתוך השם זה return "greeting"; הקונטרולר האובייקט } - ל מידע להעברת } view את מחזיר הקונטרולר greetings. html הדף בשם משתנה רושמים המודל בתול username (servlet- )ב כתבנו עכשיו עד String a. Name = request. get. Parameter(“somename”); If (a. Name == null) a. Name = “World”;

templates מנוע של : Views • view technology • Thymeleaf (in Spring Java) •

templates מנוע של : Views • view technology • Thymeleaf (in Spring Java) • EJS (in Node. JS) • Thymeleaf performs serverside rendering of the HTML. • Thymeleaf is a template engine: • parses the greeting. html template below and evaluates the th: text expression to render the value of the ”username” parameter that was set in the controller. <!DOCTYPE HTML> <html xmlns: th="http: //www. thymeleaf. org"> <head> <title>Getting Started: Serving Web Content</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <p th: text="'Hello, ' + ${username} + '!'" /> </body> </html>

 כמה דרכים להעברת נתונים : Model • the model can supply attributes used

כמה דרכים להעברת נתונים : Model • the model can supply attributes used for rendering views • To provide a view with usable data, we simply add this data to its Model object. Additionally, maps with attributes can be merged with Model instances: @Get. Mapping("/show. View. Page") public String pass. Parameters. With. Model(Model model) { Map<String, String> map = new Hash. Map<>(); map. put("spring", "mvc"); model. add. Attribute("message", ”hello"); // simple attribute model. merge. Attributes(map); // map attribute return "view. Page"; }

Map- שימוש ב : Model. Map • pass a collection of values and treat

Map- שימוש ב : Model. Map • pass a collection of values and treat these values as if they were within a Map @Get. Mapping("/print. View. Page") public String pass. Parameters. With. Model. Map(Model. Map map) { map. add. Attribute("welcome. Message", "welcome"); map. add. Attribute("message", ”hello"); return "view. Page"; }

model+view מחזירים : Model. And. View • The final interface to pass values to

model+view מחזירים : Model. And. View • The final interface to pass values to a view @Get. Mapping("/go. To. View. Page") public Model. And. View pass. Parameters. With. Model. And. View() { Model. And. View model. And. View = new Model. And. View("view. Page"); model. And. View. add. Object("message", ”hello"); return model. And. View; }

Other params • A controller method can accept various parameters such as: Session Request

Other params • A controller method can accept various parameters such as: Session Request Model: hold data for the view Binding. Result (later): holds the result of a validation and binding and contains errors that may have occurred. • Any type with @Path, @Request. Param • •

? Sessions- איך ניגשים ל הקונטרולר של בחתימה session- ה את להוסיף • יש

? Sessions- איך ניגשים ל הקונטרולר של בחתימה session- ה את להוסיף • יש @Get. Mapping("/some. Controller") public String process(Model model, Http. Session session) { String message = (String) session. get. Attribute("MY_MESSAGE"); // for example here we want to display the session variable MY_MESSAGE in the view if (message == null) { message =""; } model. add. Attribute("session. Message", message); return ”someview"; }

Cookies הקונטרולר של בחתימה request or response- ה את להוסיף • יש @Get. Mapping("/change-username")

Cookies הקונטרולר של בחתימה request or response- ה את להוסיף • יש @Get. Mapping("/change-username") public String set. Cookie(Http. Servlet. Response response) { // create a cookie Cookie cookie = new Cookie("username", ”Yosi"); //add cookie to response. add. Cookie(cookie); // more code …end of controller קריאה annotation ע״י } @Get. Mapping("/all-cookies") public String read. All. Cookies(Http. Servlet. Request request) { Cookie[] cookies = request. get. Cookies(); if (cookies != null) { // your code… } // more code …end of controller } @Get. Mapping("/get-one-cookie") public String get. Header(@Cookie. Value(name = ”username") String uname) { //. . }

/static תוכן סטטי יושב במקום מוגדר : Static files • HTML, CSS and JS

/static תוכן סטטי יושב במקום מוגדר : Static files • HTML, CSS and JS are static files that need to be served as well from within the views (linked files) • By default Spring Boot serves static content from resources in the classpath at "/static" (or "/public"). • The index. html resource is special because it is used as a "welcome page" if it exists, which means it will be served up as the root resource, i. e. at http: //localhost: 8080/ כניסה דף להיות חייב זה שלכם לאתר (landing page)

Make the application executable package hello; import org. springframework. boot. Spring. Application; import org.

Make the application executable package hello; import org. springframework. boot. Spring. Application; import org. springframework. boot. autoconfigure. Spring. Boot. Application; @Spring. Boot. Application public class Application { public static void main(String[] args) { Spring. Application. run(Application. class, args); } }

The application annotations • @Spring. Boot. Application is a convenience annotation that adds all

The application annotations • @Spring. Boot. Application is a convenience annotation that adds all of the following: • @Configuration tags the class as a source of bean definitions for the application context. • @Enable. Auto. Configuration tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings. • Normally you would add @Enable. Web. Mvc for a Spring MVC app, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath. This flags the application as a web application and activates key behaviors such as setting up a Dispatcher. Servlet. • @Component. Scan tells Spring to look for other components, configurations, and services in the hello package, allowing it to find the controllers. • The main() method uses Spring Boot’s Spring. Application. run() method to launch an application. • No web. xml file! This web application is 100% pure Java and you dont’t have to deal with configuring any plumbing or infrastructure.

? HTML האם חייבים להחזיר • Spring can handle views as well, that is

? HTML האם חייבים להחזיר • Spring can handle views as well, that is generate dynamic pages • The question is the following: should Java deal with server side only and leave the client side to other technologies? (Javascript, React) • The answer is: probably yes • What does it mean? • Your application is probably a SPA (Single page application) or has very few HTML files • All of you controllers return JSON data • Your javascript code consists in making Ajax call and modifying the DOM

thymeleaf • Thymeleaf is a Java template engine for processing and creating HTML, XML,

thymeleaf • Thymeleaf is a Java template engine for processing and creating HTML, XML, Java. Script, CSS, and text. • Must include in your HTML file: <html lang="en" xmlns: th="http: //www. thymeleaf. org"> • Automatically configured in Spring. Boot projects under Intelli. J • Can display property values • Define a bean: @Bean @Description("Spring Message Resolver") public Resource. Bundle. Message. Source message. Source() { Resource. Bundle. Message. Source message. Source = new Resource. Bundle. Message. Source(); message. Source. set. Basename("messages"); return message. Source; } • Then use in view: <span th: text="#{welcome. message}" />

thymeleaf : Display model attributes • Use the tag: th: text=”${attributename}” model. add. Attribute("server.

thymeleaf : Display model attributes • Use the tag: th: text=”${attributename}” model. add. Attribute("server. Time", date. Format. format(new Date())); Current time is <span th: text="${server. Time}" />

thymeleaf : Conditions • th: if=”${condition}” • is used to display a section of

thymeleaf : Conditions • th: if=”${condition}” • is used to display a section of the view if the condition is met. • th: unless=”${condition}” • is used to display a section of the view if the condition is not met. public class Student implements Serializable { private Integer id; private String name; Model: private Character gender; // standard getters and setters } <td> View: <span th: if="${student. gender} == 'M'" th: text="Male" /> <span th: unless="${student. gender} == 'M'" th: text="Female" /> </td>

thymeleaf : Collections • Assume the model is a collection: • The controller adds:

thymeleaf : Collections • Assume the model is a collection: • The controller adds: public class Student implements Serializable { private Integer id; private String name; // standard getters and setters } List<Student> students = new Array. List<Student>(); // logic to build student data model. add. Attribute("students", students); • We can iterate in the view with: <tbody> <tr th: each="student: ${students}"> <td th: text="${student. id}" /> <td th: text="${student. name}" /> </tr> </tbody>

Avoid HTML duplication : Thymeleaf fragments • A fragment is a piece of HTML

Avoid HTML duplication : Thymeleaf fragments • A fragment is a piece of HTML • for example <head><title>hello</title></head>) • Include fragments of HTML in the resulting view 1. Define the controllers that return the fragments : 2. Create the HTML files (fragments) 3. Include fragments in views with th: insert or th: replace <head th: insert="fragments/head. html : : head"> </head> @Controller public class Fragments. Controller { @Get. Mapping("/header") public String get. Header() { return ”header. html"; } @Get. Mapping("/footer") public String get. Footer() { return ”footer. html"; } } See: https: //www. thymeleaf. org/doc/articles/layouts. html

More on thymeleaf • Handling user input • displaying Validation Errors • Formatter (converting

More on thymeleaf • Handling user input • displaying Validation Errors • Formatter (converting and displaying) • Readings: • https: //www. thymeleaf. org/doc/articles/springmvcaccessdata. html • https: //www. baeldung. com/thymeleaf-in-spring-mvc

References • https: //spring. io/guides • https: //docs. spring. io/spring/docs/current/spring-frameworkreference/index. html • https: //howtodoinjava.

References • https: //spring. io/guides • https: //docs. spring. io/spring/docs/current/spring-frameworkreference/index. html • https: //howtodoinjava. com/spring-5 -tutorial/