- #스프링부트 #자바웹개발 #스프링프레임워크 #자바서블릿 #웹개발입문 #마이바티스 #타임리프 #스프링보안 #자바서버 #스프링mvc #자바ee #maven #pom파일 #웹애플리케이션 #웹아키텍처 #http요청응답 #restfulapi #spring초보 #spring강의 #springinitializr사용법
- #그레이트오션로드여행 #12사도바위 #멜번당일치기코스 #호주멜버른여행 #호주자연명소 #그레이트오션로드투어 #greatoceanroad #twelveapostles #melbournedaytrip
- #restapi #restful #webdevelopment #backenddevelopment #apiintegration #apiarchitecture #webserver #databaseconnection #httprequests #jsondata #frontendbackend #webapplication
- #java #spring #springboot #스프링부트 #자바 #웹개발 #백엔드 #backend #프로그래밍 #개발자 #개발공부 #코딩공부
- #git #깃 #git설치 #git초기설정 #git사용법 #버전관리 #versioncontrol #분산버전관리 #distributedversioncontrol #dvcs #중앙집중버전관리 #centralizedvcs #git기본개념 #git기초 #git초보 #commit #커밋 #repository #저장소 #branch #브랜치 #sha #sha해시 #stagingarea #스테이징영역 #workingdirect
- #테스트개발 #junit사용법 #qa #자바단위테스트 #스프링통합테스트 #테스트자동화 #자바 #java #자바개발 #신입개발자 #개발포트폴리오
- #springboot #스프링부트 #springframework #스프링프레임워크 #dependencyinjection #의존성주입 #inversionofcontrol #제어의역전 #bean #빈 #component #컴포넌트 #service #서비스 #repository #리포지토리 #applicationcontext #애플리케이션컨텍스트 #configuration
- #gapeongcafe #wolsongcafe #koreacafe #aestheticcafe #coffeelovers #europeanroastery #koreatravel #hiddenplaceseoul #mzstyle #healingvibes #hanokcafe #brunchspot #coffeetime #cafestagram #calmvibes
- #springboot #springboot기초 #스프링부트강의 #springioc #di #의존성주입 #springmvc #스프링mvc #springsecurity #springdata #springjpa
- #koreatravel #eastsea #hiddengemkorea #oceanview #travelvibes #koreanseaside #instagramspot
- #cafegerizim #vintagecafe #pyeongchangcafe #koreacafe #cafetour #hiddencafe #dessertcafe #naturecafe #healingplace #vintagestyle #countrysidevibes #peacefulspot #cozyvibes #afternoontea #cafelovers
- #restapi #restfulapi #웹개발 #백엔드개발 #api설계 #웹서버 #서버통신 #프론트백엔드연동 #api란 #개발자공부 #코딩기초 #http요청 #json데이터
- #springboot #javawebdevelopment #javaservlet #springframework #springmvc #thymeleaf #springsecurity #mybatis #javaee #httprequests #restapi #mavenbuild #webapplicationarchitecture #warvsjar #dependencyinjection #ioc #springinitializr #javabackend #webserv
- #springboot #springmvc #thymeleaf #javawebdevelopment #webapplication #modelviewcontroller #htmltemplates #formhandling #springcontroller #backenddevelopment #javadeveloper #springboottutorial #프로그래밍 #자바 #웹개발 #스프링부트 #자바웹개발
- #java #자바 #개발자 #신입개발자 #restapi #스프링부트 #스프링데이터jpa #h2데이터베이스 #dogrestapi #springboot #springdatajpa #h2database
- #가평여행 #아침고요수목원 #수목원데이트 #비오는날감성 #튤립명소 #서울근교여행 #가평데이트코스 #꽃구경명소 #비오는날힐링 #감성사진맛집 #자연힐링 #봄꽃명소 #비오는날데이트 #혼자여행추천 #사진스팟추천
- #gapyeongtrip #morningcalmgarden #rainydayvibes #flowerlover #springgarden #tulipseason #healingtravel #solotravelspot #koreanature #photospotkorea #gardenwalk #rainydaydate #springinkorea #travelkorea
- #도째비골 #동해가볼만한곳 #강원도여행 #감성여행지 #힐링여행 #국내여행추천 #동해바다 #바다뷰맛집 #강원도핫플 #말똥도나쓰 #mz감성카페 #포토존맛집 #데이트코스추천 #사진찍기좋은곳 #바다전망카페
- #스프링부트 #springboot #mybatis #스프링시큐리티 #orm #자바웹개발 #웹보안 #회원가입 #로그인인증 #데이터베이스설계 #웹개발자 #코딩블로그 #백엔드개발 #springsecurity #javaorm #해싱 #암호화 #웹앱보안 #jdbc #hashing #authentication #onionarchitecture
- #개발공부 #api기초 #신입개발자
- #평창카페 #감성카페추천 #강원도카페투어 #평창카페게리짐 #자연속카페 #빈티지카페 #유럽감성카페 #디저트맛집 #평창여행 #강원도드라이브 #분위기좋은카페 #평창감성여행 #30대여자여행 #40대여자취향저격 #감성맛집 #카페추천 #강원도핫플 #티스토리카페후기
- 너티브루키 #인천카페 #인천디저트 #디저트 #디저트맛집 #두바이초콜릿 #바클라바 #카페 #맛집
- #싱가포르여행 #가든스바이더베이 #마리나베이샌즈 #머라이언파크 #창이공항주얼 #야경맛집 #야경명소 #라떼아트카페 #싱가포르인증샷 #mrt여행 #여자혼자여행 #감성사진 #트래블로그
- #가평카페 #월송카페 #가평감성카페 #유러피안로스터리 #가평데이트코스 #가평빵맛집 #가평핫플 #가평풍경맛집 #감성카페 #한옥카페 #가평브런치 #가평여행 #감성충전 #카페추천 #힐링카페 #mz감성카페
Daily stories on Tech • Beauty • Travel
Spring MVC and Thymeleaf 본문
It’s a visible step into the world of Java web development, how Spring MVC and Thymeleaf work.
Spring MVC and Thymeleaf
Developing Web Sites from the Back-End
The figure above shows the relationship between Spring MVC and the client. Spring MVC uses HTML templates and application data to render a view for the client browser to display. The view exposes certain actions to the user, which when triggered are sent to Spring MVC, which processes the actions and renders new views for the client.
Interacting with a simple web application
In a web application, there are two components: the client that sends HTTP requests, and the server, which sends HTTP responses back. In the case of a web browser client, the responses the server sends need to be in the format of HTML, the document language of the web. The HTML that is sent to the client both defines the data that the user sees, as well as the actions a user can take — things like buttons, links, and input forms are all part of what the server is responsible for generating.
This process of generating an entire UI from HTML would be tedious if we had to do it by hand. Luckily, we don’t have to — Thymeleaf is an HTML template engine that, when used with Spring MVC, can simplify things greatly.
HTML templates
HTML templates are essentially just HTML files with special tags and attributes that can be combined with a data model by a template engine like Thymeleaf to generate fully functional HTML documents. Spring MVC provides a standard way to choose a template and supply the necessary data model when a request comes in, which allows for a truly dynamic user experience.
Data model defines how the application stores and retrieves (serialize and deserialize) the Java objects into/from the database. Data modeling starts with designing the database tables which are analogous to the Java classes (“model” classes of the MVC).
Key Terms
- GET Request: an HTTP request for data at a specific URL. This type of request cannot include any additional data.
- POST Request: and HTTP request that usually represents "posting" new data to the server. This is a common catch-all request method used for many data-bearing requests to the server.
- Dynamic: Something that is dynamic changes in response to external stimuli. In the case of HTML templates, dynamic sections of the template are ones that can be replaced or configured with data on-demand.
- Static: Something that is static does not change. In the case of HTML templates, static sections of the template are the ones that cannot be changed and will be the same no matter what data is used with the template.
- MVC: Model-View-Controller, a design pattern that emphasizes the separation of application components into those three categories or layers for more-structured user-facing application development.
Resource
https://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html
Servers, Templates, and MVC
There are three basic scenarios that comprise the majority of web-based user interaction flows.
- The first is when a user follows a link to our application from an external source, like a marketing email or google search. This kind of cold-call request means will always be a GET request, and our application's responsibility is to choose a response template (appropriate for the request URL - you don't want to send the register.html if the link the user clicked was for /shopping-cart!) and populate it with relevant application data.
- The second scenario is when a user navigates within our app, either by clicking a link or a button or performing some action we need to process on the server, like adding an item to their shopping cart. This case is very similar to the first, as it involves the server choosing a response template and populating it with data, but in this case, the action the user performs is completely up to us — since they’re initiating the action from a web page we designed, only the actions we included in that design are available. We can use this to add additional data to requests at the template-level, for example by generating each “add item to cart” button to include the item’s identifier in the request that is sent.
- The final scenario is when the user submits completely custom data to our app using form input. This is again similar to the previous two, in that the exact shape of the form is something our template design determines, and that we still need to choose a template to send in response and the data we should use to populate this template. The main difference is that the request no longer includes “safe” data — when a user can enter any data that they’d like, our application is responsible for vetting and validating that data, showing the user an error if something goes wrong.
These scenarios may seem simple, but they are the building blocks of web development. Regardless of the application, user interaction flows on the web are all built out of these basic building blocks.
MVC and You
MVC is an acronym that stands for Model-View-Controller, and it’s a common software pattern for user interface design. Traditionally, it divides the roles of components in an app into three layers:
- the Model, which is responsible for maintaining the state of an application,(Data)
- the View, which is responsible for displaying the UI to the user,
- and the Controller, which is responsible for processing user actions (sent from the View) to update the Model, and for forwarding those updates back to the View
MVC is an abstract pattern, though, and every library implements it differently. Spring MVC is built around the browser as a platform, and it organizes these roles like this:
- HTML templates are the views — each one represents a specific screen or screen component that the user is shown.
- Spring beans are the controllers — specifically, Spring MVC gives an @Controller annotation that we can use to register our beans as controllers. Think of Spring bean controllers as specialized application components that can define methods to handle specific user requests. Those methods are responsible for choosing the HTML template that is generated in response, as well as for populating the Model object for that template.
- Model objects are the models - every controller method can take an optional Model argument, and by reading and changing the data inside of it, the controller can read user-submitted data and populate the template with the changes. Think of the Model class a simple data-transfer object: something that can store various bits of data with keys to look that data up, and that can be passed between the browser, the template engine, and the controller to facilitate the transfer of data between the user and the application.
In order to start using Spring MVC, we need two main elements: an HTML template to define the user interface, and a Spring MVC @Controller-annotated bean to serve that template and populate it with data.
In our example so far, our “template” is actually just a static HTML page that displays a greeting. The main takeaway about templates so far is to remember to place them in the right folder — src/main/resources/templates under the project root directory. When we choose a template in our controller, we do so by specifying the template name we want to load - our home.html template in the example is simply referred to as "home". This will only work if your templates are in the right folder, so always double check!
To set up a basic controller to serve this template, we created a new class called HomeControllerand annotated it with @Controller. This registers the class as a Spring bean and makes it eligible for request handling. That's why we can't just use @Component - Spring MVC only looks at controllers, not all Spring beans.
In order to actually bind the controller to a specific request URL — like /home in our example - we have to define a method in the controller and annotate it with @RequestMapping. We also have to return a String from this method - this is the name of the template we want to render. For this first step into web development, that's all we do - return the String "home" to indicate that we want the home.html template to be rendered when a user requests the /home URL.
Basic User Flow
In order to actually render dynamic data in a template, we again need to approach it from both the template and the controller.
In the template, we need to add Thymeleaf attributes to our HTML. In our example so far, we added the th:text attribute to the heading we want to be dynamic, like so:
<h1 th:text="${welcomeMessage}">Hello, homepage!</h1>
This attribute will cause Thymeleaf to replace the text inside the h1 tag (Hello, homepage!) with a string generated by evaluating the expression in the th:text attribute (${welcomeMessage}). The syntax of this expression is fairly simple: the ${} indicates an expression to evaluate, and by using a name like welcomeMessage inside of it, we're telling Thymeleaf to look up a value in the model supplied for this template with the same name.
For that to work, though, we need to add a value named welcomeMessage to the model - and we do that in the controller method like so:
@RequestMapping("/home")
public String getHomePage(Model model) {
model.addAttribute("welcomeMessage", "Hi Hello");
return "home";
}
First we need to add an argument to the controller method — the Model object you see above. This is a special class that Spring MVC will send to Thymeleaf to render the template, and we can set various attributes on it to add named values. As you can see, we're adding a value of "Hi Hello" to the model with the name "welcomeMessage" - which is exactly the name we're referencing in our template! Now when we render the template, the message Hi Hello will appear on the web page instead of Hello, homepage!
We can replace the hardcoded "Hi Hello" string in our controller with any Java value or expression, and it will be set every time the controller method is called, which means every time a request comes in for /home. That means we can set it dynamically, even based on the request that comes in. If we replace it with Instant.now().toString(), we end up with a welcome message that shows the current time, and updates every time we reload the page.
The Spring MVC Architecture
The figure above shows the Spring MVC’s architecture. The browser represents the view, and requests from the browser are user actions. When Spring MVC processes a request, it creates a Model object that represents the dynamic data associated with the view and passes it to a controller method that matches the request. The controller updates the model and chooses a template to render in response. Spring MVC passes the template and the updated model to Thymeleaf, which generates an updated view, which Spring sends in response to the browser.
Key Terms
- MVC: MVC is an acronym that stands for Model-View-Controller, and it’s a common software pattern for user interface design
- Model: in MVC, the Model is responsible for maintaining the state of an application,
- View: in MVC, the View is responsible for displaying the UI to the user,
- Controller: in MVC, the Controller is responsible for processing user actions (sent from the View) to update the Model, and for forwarding those updates back to the View
- Template: In software development, templates are used in many different contexts — in general, they are a way to define some often-repeated or reused text or code in a specific format, like HTML, along with code hooks that indicate portions of the template that should be replaced dynamically when the template is rendered. In our context, we mostly use Thymeleaf’s HTML templates, which mostly look like plain HTML with a few extra Thymeleaf-specific attributes. These attributes are our code hooks, and allow us to define what data Thymeleaf uses when generating the final HTML from our template.
Further Research
- https://spring.io/guides/gs/serving-web-content/
- https://uniandes-se4ma.gitlab.io/books/chapter8/mvc-mvvm-mv-mvwhat.html
HTML Templates with Thymeleaf
The nature of Spring MVC’s data flow — the controller has to provide the data for the template it wants to render — means that often, when designing a new user-facing feature, it makes sense to start with the template.
Thymeleaf is the HTML template engine we’re using in this class, which means that it’s a library that can take a template, a data model, and combine them to generate a final HTML document.
The way that Thymeleaf applies the data model to the template is based on the Thymeleaf attributes we add to the template, like th:text on MVC. These attributes can have complex expressions as their values, which are processed by Thymeleaf in the context of the data model provided.
In addition to setting text values, we can use Thymeleaf attributes to perform basic control flow in our templates. The main two types of control flow in templates are iteration and conditional rendering.
Iteration in Thymeleaf templates works very similarly to an enhanced for-loop in Java. The main attribute used in template iteration is th:each, and its use looks like this:
<h1 th:each="msg : ${greetings}" th:text="${msg}">Hello, homepage!</h1>
We can read the attribute th:each="msg : ${greetings}" as "for each msg in greetings", and it essentially means "repeatedly render this element for each value in the greetings collection, and name that element msg for any expressions that need that name to have a value associated with it.
So in this example, the h1 tag will be repeatedly rendered, once for each element in greetings, and the text rendered by th:text="${msg}" will be the current element of greetings being rendered. If greetings contained the Strings "Hi" and "Hello", the final rendered html would be
<h1>Hi</h1>
<h1>Hello</h1>
Conditional rendering in Thymeleaf usually looks like an if statement in Java, or occasionally a switch statement. The attribute we examined in the example was th:unless, as in:
<h1 th:unless="${msg.contains('goodbye')}" th:text="${msg}">Hello, homepage!</h1>
In this case, if the msg contains the String "goodbye", the h1 tag will not be rendered. This is particularly useful when choosing whether or not to render an error message, for example. If you need the opposite condition, in this case only showing messages that contain "goodbye", you can simply replace the th:unless with th:if.
How Thymeleaf Renders a View
The figure above shows how Thymeleaf renders a view. In order to render a view, Thymeleaf must be given a template and a model to use. Thymeleaf scans through the template to find dynamic data expressions and resolves the variables in those expressions using the model. Some dynamic data expressions result in iterated or conditional rendering in addition to more typical text replacement.
Key Terms
- User Action: Broadly, a user action is simply some specific action a user can take, provided by the user interface they’re interacting with. In the case of web applications, we usually think of user actions as clicks on a web page that often result in a HTTP request sent to the backend.
- Prototype/Wireframe In the development process for a web application, it’s common to first design the full HTML and CSS for all of the screens a user is expected to see. These pages have no actual functionality, and are usually called prototypes. Wireframes are an even earlier product of the design process, and usually are simple images that show what the prototypes should look like.
Further Reading
- https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#introducing-thymeleaf
- https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#standard-expression-syntax
Solution: HTML Templates with Thymeleaf
This example should be pretty simple. Here’s the <body> text of our webpage:
<body>
<form action="#" th:action="@{'/simplehome'}" method="POST">
<input type="submit" value="Visit me">
</form>
<h1 th:if="${firstVisit}">Hello, homepage!</h1>
<h1 th:unless="${firstVisit}">Welcome back!</h1>
</body>
You can see we took the following steps:
- Set th:action to our /simplehome endpoint
- Set the method of our form to POST
- Used th:if and th:unless to choose which message to display depending on the variable firstVisit.
Here(https://github.com/udacity/nd035-c1-spring-boot-basics-examples/tree/master/udacity-jwdnd-c1-l3-html-templates-master) is the complete solution code with analogous variable names and corresponding values.
Connecting Controllers to Templates
The final piece of the Spring MVC puzzle we need to build fully capable web apps is the ability to handle user-submitted data. As before, there are two main components to this, one on the template side, the other on the controller side.
On the template side, we need to define input fields for each piece of data we want to capture, and a <form> element to group them. When the form is submitted, the data will be encoded in the HTTP request that is sent, and can be extracted on the Spring side.
On the Spring side of things, we need to define a POJO to hold the form data, by defining this POJO we can pre-fill the form by setting its fields and adding it as a Model attribute when first rendering the template, and Spring can automatically extract the request data into that POJO when the form is submitted. Let’s see how that works!
User-Inputted Data
we looked at the HTML tags and Thymeleaf attribute we need to set up a form for the user to fill and submit to the server. Here’s the template code saw:
<form th:object="${newMessage}" th:action="@{/home}" action="#" method="POST">
<input th:field="*{text}" type="text">
<input type="submit">
</form>
We use the th:object attribute to choose the POJO our form data should be added to, and the th:actionattribute to choose the URL to send the form submission HTTP request to. We use the special @{} syntax in the latter to tell Thymeleaf to make sure the URL is always relative to the actual server address - this doesn't make a huge difference in our current project, but it's good practice when referring to URLs on our server in a Thymleaf template.
We also set method="POST" on the form to set the HTTP method of the resulting request. This is important! Remember that GET requests cannot contain any custom data - we need to use POST for our form data to actually get sent!
In order to bind the individual form input data fields to the form-backing POJO’s fields, we need to add the th:field attribute. We also need to use another special Thymeleaf expression syntax - *{}. This allows us to refer to fields on the form-backing POJO without using dot syntax - th:field="*{text}" in this example is equivalent to th:field="${newMessage.text}".
action="#"
what do <form action=”#”> and <form method=”post” action=”#”> do?
https://stackoverflow.com/questions/8395269/what-do-form-action-and-form-method-post-action-do
Persisting Data
we looked at how to handle user-submitted data from the Spring controller side of things. Here are the finalized controller methods we saw:
@GetMapping("/home")
public String getHomePage(@ModelAttribute("newMessage") MessageForm newMessage, Model model) {
model.addAttribute("greetings", this.messageListService.getMessages());
return "home";
}
@PostMapping("/home")
public String addMessage(@ModelAttribute("newMessage") MessageForm messageForm, Model model) {
messageListService.addMessage(messageForm.getText());
model.addAttribute("greetings", messageListService.getMessages());
messageForm.setText("");
return "home";
}
The key elements to focus on are the new arguments to each of these methods — the MessageFormclass is a POJO specifically designed to hold the form data.
For the GET request handling method, we declare the MessageForm argument to ensure that the object exists and is added to the model by Spring automatically. This is necessary, because Thymeleaf needs an object with the name newMessage to be present in the model to render properly, even if there isn't any data in the object yet.
For the POST request handling method, we declare the MessageForm argument to tell Spring that it should look for data that matches that in the body of the request we're handling. Spring will then automatically extract that data and put it in a MessageForm object before calling our method, passing it to us so we can use the data as we see fit.
In both cases, we’re annotating this argument with @ModelAttribute. This allows us to specify that Spring should add the object to our Model before asking Thymeleaf to render the template. That means we don't have to add it manually! Pretty handy.
Key Terms
- Form-Backing Object: This is a term used by Spring MVC and Thymeleaf to mean an object that represents the data contained in a form. On the Spring side, this is usually an additional argument to the relevant Controller method, and on the Thymeleaf side, this is referred to in the th:objectattribute on the form.
Further Research
Solution: Connecting Controllers to Templates
Here’s the <body> text that completes this assignment:
<body>
<form action="#" th:action="@{'/animal'}" th:object="${messageForm}" method="POST">
<label for="animalText">Enter an Animal: </label>
<input type="text" id="animalText" name="animalText" th:field="*{animalName}">
<label for="adjective">Enter an Adjective:</label>
<input type="text" id="adjective" name="adjective" th:field="*{adjective}">
<input type="submit">
</form>
<h1 th:unless="${#lists.size(greetings) > 5}" th:each="msg : ${greetings}" th:text="${msg}">Hello, homepage!</h1>
<h1 th:if="${#lists.size(greetings) > 5}">I think that's enough!</h1>
</body>
You can see we made a few revisions to the <form> element:
- We added th:action to set the target of the form submission.
- We used th:object to bind the form to messageForm.
- We added a method=”POST” attribute.
We also added the th:field attribute to our input to reference the animalName and adjectivevalues on our messageForm.
To display the list of greetings, we use th:each and set the th:text for each row to the msg value.
Lastly, we use th:if and th:unless to show or hide our two text elements. Note that they don’t have to be in any particular order. th:if and th:unless both can operate independently.
Here(https://github.com/udacity/nd035-c1-spring-boot-basics-examples/tree/master/udacity-jwdnd-c1-l3-connecting-controllers-2-master) is the complete solution code with analogous variable names and corresponding values.
Special Controller Inputs (File Upload)
Sometimes when we build web applications with Spring, we need to account for special request types and data formats. The key takeaway from this edge case is that usually, we can accomplish this by adding the correct argument to our controller method. In this example, we looked at MultiPartFile, a special request data class provided by Spring to handle large file uploads. As with any special data type, simply by adding it as an argument to our controller method, Spring knows to treat the incoming request appropriately.
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/multipart/MultipartFile.htmlFurther Research
https://github.com/spring-guides/gs-uploading-files
Exercise: Final Review
For this final review, we’ll be building on our project to develop a rudimentary chat application, where users can submit messages along with their username, and those messages (along with the usernames of the users who sent them) will be visible to any user that navigates to the /chat URL. Additionally, users should be able to select a message "mode": either Say, Shout, or Whisper. Say should display the message as written, while Shout should display the message in all-uppercase, and Whisper should display the message in all-lowercase. In order to accomplish this, you'll have to take the following steps:
- Disable Spring Security. let’s comment out the dependency in our pom.xml file. Here are the dependencies that should be commented out:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
2. Add a chat.html template for the main application screen. This template should have two parts: First, a form that allows users to submit their username, the message text they'd like to send to the chat, and the message "mode": Say, Shout, or Whisper. Second, some way to display the list of messages that have been sent so far. Here's some starter code for the form:
<form>
<label for="username">Username:</label>
<input id="username" type="text">
<label for="messageText">Message Text:</label>
<input id="messageText" type="text">
<label for="messageType">Message Type: </label>
<select id="messageType">
<option selected>Say</option>
<option>Shout</option>
<option>Whisper</option>
</select>
<input type="submit">
</form>
You’re going to have to add Thymeleaf attributes to make this form work with the backend, and you might want to refer to the official Thymeleaf documentation on how to properly set up <select> tags in a form.
- Add a ChatForm class to hold the chat form data. If we have a form, we need a form-backing object. Make sure its fields match the form input elements!
- Add a ChatMessage class to hold the displayed message information. Since we are displaying two pieces of data for each message, the message text and the sender's username, we should create a class to hold both at once.
- Update the MessageService class to store a List<ChatMessage> as the chat history. Since we want to keep track of many messages over time, we need a place to put them!
- Update the MessageService class to have an addMessage method. This method will be called by the controller to add a submitted message to the message list stored by the MessageService.
- Add a ChatController class to serve the chat.html template and handle new message submissions. We can't have a Spring MVC app without controllers! This controller should serve the chat.html template when a GET request comes in under the /chat URL, and it should handle POST requests at the same URL as new message submissions.
- [BONUS] add a list of banned words. Use that list to conditionally render messages on the page — messages that contain one or more banned words should not be displayed.
- [EXTRA BONUS] Add some style! Designing an attractive website is unfortunately out of scope for this class, but that doesn’t mean you can’t take matters into your own hands! If you feel comfortable writing your own styling code, add CSS and/or JavaScript files to make the app a little easier on the eyes. If you don’t have a lot of experience with that kind of thing, but you’d like to learn, Bootstrap is a great place to start!
Solution: Final Review
Glossary
- GET Request: an HTTP request for data at a specific URL. This type of request cannot include any additional data.
- POST Request: and HTTP request that usually represents "posting" new data to the server. This is a common catch-all request method used for many data-bearing requests to the server.
- Dynamic: Something that is dynamic changes in response to external stimuli. In the case of HTML templates, dynamic sections of the template are ones that can be replaced or configured with data on-demand.
- Static: Something that is static does not change. In the case of HTML templates, static sections of the template are the ones that cannot be changed and will be the same no matter what data is used with the template.
- MVC: Model-View-Controller, a design pattern that emphasizes the separation of application components into those three categories or layers for more-structured user-facing application development.
- Model: in MVC, the Model is responsible for maintaining the state of an application,
- View: in MVC, the View is responsible for displaying the UI to the user,
- Controller: in MVC, the Controller is responsible for processing user actions (sent from the View) to update the Model, and for forwarding those updates back to the View
- Template: In software development, templates are used in many different contexts — in general, they are a way to define some often-repeated or reused text or code in a specific format, like HTML, along with code hooks that indicate portions of the template that should be replaced dynamically when the template is rendered. In our context, we mostly use Thymeleaf’s HTML templates, which mostly look like plain HTML with a few extra Thymeleaf-specific attributes. These attributes are our code hooks, and allow us to define what data Thymeleaf uses when generating the final HTML from our template.
- User Action: Broadly, a user action is simply some specific action a user can take, provided by the user interface they’re interacting with. In the case of web applications, we usually think of user actions as clicks on a web page that often result in a HTTP request sent to the backend.
- Prototype/Wireframe In the development process for a web application, it’s common to first design the full HTML and CSS for all of the screens a user is expected to see. These pages have no actual functionality, and are usually called prototypes. Wireframes are an even earlier product of the design process, and usually are simple images that show what the prototypes should look like.
- Form-Backing Object: This is a term used by Spring MVC and Thymeleaf to mean an object that represents the data contained in a form. On the Spring side, this is usually an additional argument to the relevant Controller method, and on the Thymeleaf side, this is referred to in the th:objectattribute on the form.
'Tech > Java Web Development' 카테고리의 다른 글
Testing (0) | 2025.05.12 |
---|---|
Data Persistence & Security (1) | 2025.05.11 |
Spring boot for web development (0) | 2025.05.09 |
Web Development in Java (2) | 2025.05.08 |
Spring boot (1) | 2025.05.07 |