Article Directory
[Shang Silicon Valley] SpringBoot2 Zero-Basic Introductory Tutorial - Lecturer: Lei Fengyang
Notes
The road is still going on, the dream is still waiting
1. View analysis
View analysis: It is the process of spring boot processing the request and wanting to jump to a certain page. The commonly used method in the past is forwarding or redirecting to a JSP page. Now spring boot is used, because the spring boot packaging method is jar package , The jar package is a compressed package. JSP does not support the way of compiling in the compressed package, so spring boot does not support JSP by default. If you want to use the page rendering function and page jump, you need to introduce third-party template engine technology to achieve page rendering.
1.1 Third-party template engine technology supported by spring boot
In the scenario starter, check out the template engine technologies supported by spring boot.
Name | Description |
---|---|
spring-boot-starter-freemarker | Starter for building MVC web applications using FreeMarker views |
spring-boot-starter-groovy-templates | Starter for building MVC web applications using Groovy Templates views |
spring-boot-starter-thymeleaf | Starter for building MVC web applications using Thymeleaf views |
1.2. Principle process of view analysis
- 1. During the processing of the target method, all data will be placed in the ModelAndViewContainer. Include data and view addresses
- 2. The parameter of the method is a custom type object (determined from the request parameter), put it back in the ModelAndViewContainer
- 3. ModelAndView (data and view address) will be returned after any target method is executed.
- 4. processDispatchResult processes the dispatch result (how to respond to page changes)
- 1. render(mv, request, response); perform page rendering logic
- 1. Obtain the View object according to the String return value of the method [defining the rendering logic of the page]
- 1. All view resolvers try to get the View object according to the current return value
- 2. Got redirect:/main.html --> Thymeleaf new RedirectView()
- 3. ContentNegotiationViewResolver contains all the following view resolvers, and internally uses all the following view resolvers to obtain view objects.
- 4. view.render(mv.getModelInternal(), request, response); The view object calls the custom render to render the page
- How does RedirectView render [redirect to a page]
- 1. Obtain the target url address
- 2、response.sendRedirect(encodedURL);
- 1. Obtain the View object according to the String return value of the method [defining the rendering logic of the page]
- 1. render(mv, request, response); perform page rendering logic
View resolution:
- The return value starts with forward:: new InternalResourceView(forwardUrl); --> Forward request.getRequestDispatcher(path).forward(request, response);
- The return value starts with redirect:: new RedirectView() -- "render is redirection
- The return value is a plain string: new ThymeleafView() -->
Custom View Parser + Custom View; Dachang Academy.
2. Template engine - Thymeleaf
2.1 Introduction to thymeleaf
Thymeleaf is a modern server-side Java template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text.
Modern, server-side Java templating engine
2.2. Basic grammar
1. Expression
expression name | grammar | use |
---|---|---|
variable value | ${…} | Get request field, session field, object and other values |
select variable | *{…} | Get context object value |
information | #{…} | Get the internationalization equivalent |
Link | @{…} | generate link |
fragment expression | ~{…} | jsp:include function, introducing public page fragments |
2. Literal volume
Text values: 'one text' , 'Another one!' ,…
Numbers: 0 , 34 , 3.0 , 12.3 ,…
Boolean values: true , false
Null values: null
Variables: one, two,… Variables cannot have spaces
3. Text manipulation
String concatenation: +
variable substitution: |The name is ${name}|
4. Mathematical operations
Operators: + , - , * , / , %
5. Boolean operations
Operators: and , or
Unary operations: ! , not
6. Comparison operation
Comparison: > , < , >= , <= ( gt , lt , ge , le ) Equality: == , != ( eq , ne )
7. Conditional operation
If-then: (if) ? (then)
If-then-else: (if) ? (then) : (else)
Default: (value) ?: (defaultvalue)
8. Special operations
no-op: _
2.3. Set attribute value -th:attr
set a single value
<form action="subscribe.html" th:attr="action=@{/subscribe}">
<fieldset>
<input type="text" name="email" />
<input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/>
</fieldset>
</form>
set multiple values
<img src="../../images/gtvglogo.png" th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />
Alternatives to the above two th:xxxx
<input type="submit" value="Subscribe!" th:value="#{subscribe.submit}"/>
<form action="subscribe.html" th:action="@{/subscribe}">
2.4. Iteration
<tr th:each="prod : ${prods}">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
<td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
<tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
<td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
2.5, conditional operation
<a href="comments.html"
th:href="@{/product/comments(prodId=${prod.id})}"
th:if="${not #lists.isEmpty(prod.comments)}">view</a>
<div th:switch="${user.role}">
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
<p th:case="*">User is some other thing</p>
</div>
2.6. Attribute Priority
3. Use of Thymeleaf
3.1. Introducing Starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
3.2, automatic configuration thymeleaf
1. Configuration class
位置:org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(ThymeleafProperties.class)
@ConditionalOnClass({
TemplateMode.class, SpringTemplateEngine.class })
@AutoConfigureAfter({
WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
public class ThymeleafAutoConfiguration {
}
2. Automatically configured strategies
- 1. All configuration values of thymeleaf are in ThymeleafProperties
- 2. Configure SpringTemplateEngine
- 3. Configure ThymeleafViewResolver
- 4. We only need to directly develop the page
3. The default path of page resources
// 前缀
public static final String DEFAULT_PREFIX = "classpath:/templates/";
// 后缀
public static final String DEFAULT_SUFFIX = ".html"; //xxx.html
3.3. Page development
The namespace of thymeleaf, after adding it, there will be a prompt in the page development.
The thymeleaf engine parses the page and must have a namespace.
<html xmlns:th="http://www.thymeleaf.org">
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 th:text="${msg}">哈哈</h1>
<h2>
<a href="www.atguigu.com" th:href="${link}">去百度</a> <br/>
<a href="www.atguigu.com" th:href="@{link}">去百度2</a>
</h2>
</body>
</html>
4. Build a background management system
4.1. Project creation
thymeleaf、web-starter、devtools、lombok
4.2. Static resource processing
Automatically configured, we just need to put all static resources in the static folder
4.3. Path construction
th:action=“@{/login}”
4.4. Template extraction
th:insert/replace/include
4.5, page jump
@PostMapping("/login")
public String main(User user, HttpSession session, Model model){
if(StringUtils.hasLength(user.getUserName()) && "123456".equals(user.getPassword())){
//把登陆成功的用户保存起来
session.setAttribute("loginUser",user);
//登录成功重定向到main.html; 重定向防止表单重复提交
return "redirect:/main.html";
}else {
model.addAttribute("msg","账号密码错误");
//回到登录页面
return "login";
}
}
4.6. Data rendering
@GetMapping("/dynamic_table")
public String dynamic_table(Model model){
//表格内容的遍历
List<User> users = Arrays.asList(new User("zhangsan", "123456"),
new User("lisi", "123444"),
new User("haha", "aaaaa"),
new User("hehe ", "aaddd"));
model.addAttribute("users",users);
return "table/dynamic_table";
}
<table class="display table table-bordered" id="hidden-table-info">
<thead>
<tr>
<th>#</th>
<th>用户名</th>
<th>密码</th>
</tr>
</thead>
<tbody>
<tr class="gradeX" th:each="user,stats:${users}">
<td th:text="${stats.count}">Trident</td>
<td th:text="${user.userName}">Internet</td>
<td >[[${user.password}]]</td>
</tr>
</tbody>
</table>