Spring Boot提供了spring-boot-starter-web(嵌入tomcat和Spring MVC的依赖)为Web开发做支持。


Thymeleaf基础知识
Thymeleaf是一个java类库,是一个xml/xhtml/html5的模板引擎,可以作为MVC的Web应用的View层。提供了额外的模块与Spring MVC集成,可以使用Thymeleaf完全替代jsp。
Thymeleaf网站:http://www.thymelead.org
1.引入Thymeleaf,代码:
<htmlxmlns:th="http://www.thymeleaf.org">
<!--通过xmlns:th="http://www.thymeleaf.org"命名空间,将镜头页面转换为动态的视图,需要进行动态处理的元素将使用“th:”为前缀-->
<head>
<metacontent="text/html;charset=UTF-8"/>
<linkth:src="@{bootstrap/css/bootstrap.min.css}"rel="stylesheet"/>
<linkth:src="@{bootstrap/css/bootstrap-theme.min.css}"rel="stylesheet"/>
</head>
<body>
<scriptth:src="@{jquery-1.10.2.min.js}"type="text/javascript"></script>
<!--通过“@{}”引用Web静态资源,这在jsp极易出错-->
<scriptth:src="@{bootstrap/js/bootstrap.min.js}"></script>
</body>
</html>
2.访问Model的数据
<divclass="panel panel-primary">
<divclass="panel-heading">
<h3class="panel-title"></h3>
</div>
<divclass="panel-body">
<spanth:text="${singlePerson.name}}"></span>
<!--使用<span th:text="${singlePerson.name}}"></span>访问model中的singlePerson的name属性-->
<!--注意:需要处理的动态内容需要加上“th:”前缀-->
</div>
</div>
3.model中的数据迭代
<divclass="panel panel-primary">
<divclass="panel-heading">
<h3class="panel-title">列表</h3>
</div>
<divclass="panel-body">
<ulclass="list-group">
<liclass="list-group-item"th:each="person:${people}">
<spanth:text="${person.name}"></span>
</li>
</ul>
<!--使用th:each来做循环迭代th:each="person:${people}",person作为迭代元素来使用-->
</div>
</div>
4.数据判断
<divth:if="${not #lists.isEmpty(people)}">
<!--通过使用${not #lists.isEmpty(people)}表达式判断peoples是否为空。
Thymeleaf支持>、<、>=、<=、==、!=作为比较条件,同时也支持将SpringEL表达式语言用于条件中-->
<divclass="panel panel-primary">
<divclass="panel-heading">
<h3class="panel-title">列表</h3>
</div>
<divclass="panel-body">
<ulclass="list-group">
<liclass="list-group-item"th:each="person:${people}">
<spanth:text="${person.name}"></span>
</li>
</ul>
</div>
</div>
</div>
5.在javascript中访问Model
<scriptth:inline="javascript">
//通过th:inline="javascript"添加到script标签,这样Javascript代码即可访问model属性
//通过[[${}}]]格式获取实际的值
varsingle=[[${singlePerson}]];
console.log(single.name+"/"+single.age)
</script>

html通过按钮获得model的值
<liclass="list-group-item"th:each="person:${people}">
<spanth:text="${person.name}"></span>
<buttonclass="btn"th:onclick="'getName(\''+${person.name}+'\');'"></button>
</li>




与Spring MVC集成
在Spring MVC中,集成模板引擎需要定义ViewResolver,而ViewResolver需要定义一个View
例如:
@Bean//映射路径和实际页面的位置
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/classes/views/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
return viewResolver;
}

Thymeleaf定义了org.thymeleaf.spring4.view.ThymeleafView和org.thymeleaf.spring4.view.ThymeleafViewResolver(默认使用ThymeleafView作为View)
Thymeleaf提供了SpringTemplateEngine类,用来驱动在Spring MVC下使用Thymeleaf模板引擎,提供了TemplateResolver用来设置通用的模板引擎(包含前后缀)
@Bean
publicTemplateResolver templateResolver(){
TemplateResolver templateResolver=newServletContextTemplateResolver();
templateResolver.setPrefix("/WEB-INF/templates");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML5");
returntemplateResolver;
}
@Bean
publicSpringTemplateEngine templateEngine(){
SpringTemplateEngine templateEngine=newSpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
returntemplateEngine;
}
@Bean
publicThymeleafViewResolver thymeleafViewResolver(){
ThymeleafViewResolver thymeleafViewResolver=newThymeleafViewResolver();
thymeleafViewResolver.setTemplateEngine(templateEngine());
returnthymeleafViewResolver;
}

Spring Boot的Thymeleaf支持
Spring Boot通过org.springframework.boot.autoconfigure.thymeleaf包对Thymeleaf进行了自动配置



实战
1.新建Spring Boot项目,选择Thymeleaf依赖
Spring Boot的web开发(1)
Spring Boot的web开发(1)
2.javaBean示例
packagecom.hand;

/**
* Created by lqy on 2017-11-26.
*/
public classPerson {
privateString name;
private intage;
publicPerson(){
super();
}
publicPerson(String name,intage){
super();
this.name=name;
this.age=age;
}
publicString getName(){
returnname;
}
public intgetAge(){
returnage;
}
public voidsetName(){
this.name=name;
}
public voidsetAge(){
this.age=age;
}
}
3.脚本样式静态文件
Spring Boot的web开发(1)
Spring Boot的web开发(1)
4.演示页面
Spring Boot的web开发(1)
Spring Boot的web开发(1)
代码如下:
<htmlxmlns:th="http://www.thymeleaf.org">
<head>
<metacontent="text/html;charset=UTF-8"/>
<metahttp-equiv="X-UA-Compatible"content="IE=edge"/>
<metaname="viewport"content="width=device-width, initial-scale=1"/>
<linkth:href="@{bootstrap/css/bootstrap.min.css}"rel="stylesheet"/>
<linkth:href="@{bootstrap/css/bootstrap-theme.min.css}"rel="stylesheet"/>
</head>
<body>
<divclass="panel panel-primary">
<divclass="panel-heading">
<h3class="panel-title">访问model</h3>
</div>
<divclass="panel-body">
<spanth:text="${singlePerson.name}"></span>
</div>
</div>
<divth:if="${not #lists.isEmpty(people)}">
<divclass="panel panel-primary">
<divclass="panel-heading">
<h3class="panel-title">列表</h3>
</div>
<divclass="panel-body">
<ulclass="list-group">
<liclass="list-group-item"th:each="person:${people}">
<spanth:text="${person.name}"></span>
<spanth:text="${person.age}"></span>
<buttonclass="btn"th:onclick="'getName(\'' + ${person.name} + '\');'">获得名字</button>
</li>
</ul>
</div>
</div>
</div>
<scriptth:src="@{jquery-1.10.2.min.js}"type="text/javascript"></script><!-- 2 -->
<scriptth:src="@{bootstrap/js/bootstrap.min.js}"></script><!-- 2 -->
<scriptth:inline="javascript">
varsingle= [[${singlePerson}]];
console.log(single.name+"/"+single.age)
functiongetName(name){
console.log(name);
}
</script>
</body>
</html>
5.数据准备
做一个控制器
packagecom.hand;

importorg.springframework.stereotype.Controller;
importorg.springframework.ui.Model;
importorg.springframework.web.bind.annotation.RequestMapping;

importjava.util.ArrayList;
importjava.util.List;

/**
* Created by lqy on 2017-11-26.
*/
@Controller
public classPerService {
@RequestMapping("/")
publicString index(Model model){
Person single =newPerson("aa",11);

List<Person> people =newArrayList<Person>();
Person p1 =newPerson("xx",11);
Person p2 =newPerson("yy",22);
Person p3 =newPerson("zz",33);
people.add(p1);
people.add(p2);
people.add(p3);

model.addAttribute("singlePerson", single);
model.addAttribute("people", people);
return"index";
}
}
入口类
packagecom.hand;

importorg.springframework.boot.SpringApplication;
importorg.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public classSpringThymeleafApplication {

public static voidmain(String[] args) {
SpringApplication.run(SpringThymeleafApplication.class, args);
}
}
最终访问效果
Spring Boot的web开发(1)
单击zz可以得到名字
Spring Boot的web开发(1)


Web相关配置
1.Spring提供的自动配置
1.自动配置的ViewResolver
(1)ContentNegotiatingViewResolver
Spring MVC提供的特殊ViewResolver,ContentNegotiatingViewResolver不是自己处理View,而是代理给不同的ViewResolver来处理不同的View,具备很高的优先级。
(2)BeanNameViewResolver
在控制器(@Controller)中的一个方法返回值的字符串(即视图名)会根据BeanNameViewResolver去查找Bean的名称为返回字符串的View渲染视图。
举例:
定义BeanNameViewResolver的Bean
@Bean
publicBeanNameViewResolver beanNameViewResolver(){
BeanNameViewResolver resolver=newBeanNameViewResolver();
returnresolver;
}
定义一个View的Bean
@Bean
publicMappingJackson2JsonView jsonView(){
MappingJackson2JsonView jsonView=newMappingJackson2JsonView();
returnjsonView;
}
在控制器中返回值字符串为jsonView,它会找Bean名字为jsonView的视图渲染
@RequestMapping(value ="/json",produces ={MediaType.APPLICATION_JSON_VALUE} )
publicString json(Model model){
Person single=newPerson("aa",11);
model.addAttribute("single",single);
return"jsonView";
}
(3)InternalResourceViewResolver
这是极为常用的ViewResolver,主要通过设置前后缀以及控制器中方法返回视图名的字符串,得到实际页面
@Bean
@ConditionalOnMissingBean(InternalResourceViewResolver.class)
publicInternalResourceViewResolver defaultViewResolver(){
InternalResourceViewResolver resolver=newInternalResourceViewResolver();
resolver.setPrefix(this.prefix);
resolver.setSuffix(this.suffix);
returnresolver;
}
2.自动配置的静态资源
在自动配置类的addResourceHandlers方法中定义了以下静态资源的自动配置
(1)类路径文件
把类路径下的/static、/public、/resources和/MEAT-INF/resources文件夹下的静态文件直接映射成/**,通过http://localhost:8080/**直接访问
(2)webjar(将我们脚本框架封装在Jar包中的jar包)
把webjar的/META-INF/resources/webjars/下的静态文件映射为/webjar/**,可以通过http://localhost:8080/webjar/**直接访问
3.自动配置的Formatter和Converter(具体查看WebMvcAutoConfiguration类addFormatters方法)
只要定义了Converter、GenericConverter和Formatter接口的实现类的Bean,这些Bean就自动注册到Spring MVC中
4.自动配置的HttpMessageConverters(具体查看WebMvcAutoConfiguration类)
5.静态首页的支持
把静态index.html文件放置在如下目录:
classpath:/META-INF/resources/index.html
classpath:/resources/index.html
classpath:/static/index.html
classpath:/public/index.html


2.接管Spring Boot的Web配置
如果Spring Boot提供的Spring MVC不满足要求,可以通过定义一个(含有@Configuratioon和@EnableWebMvc注解)配置类来实现完全自己控制的MVC配置。
当需要在Spring Boot提供的基础上额外加自己的配置时,可以定义一个配置类继承WebMvcConfigurerAdapter,无须使用@EnableWebMvc注解。
例如:
@Configuration
public classtestssss extendsWebMvcConfigurerAdapter{
@Override
public voidaddViewControllers(ViewControllerRegistry registry){
registry.addViewController("/xx").setViewName("/xx");
}
}
提醒:再次重写的addViewControllers方法不会覆盖WebMvcConfigurerAdapter中的方法。我们的配置和Spring Boot自动配置可以同时生效


3.注册Servlet、Filter、Listener
使用嵌入式的Servlet容器(Tomcat、Jetty)时,通过将Servlet、Filter、Listener声明为Spring Bean而达到注册效果。或者注册ServletRegistrationBean、FilterRegistrationBean 和ServletListenerRegistrationBean的Bean
(1)直接注册Bean:
@Bean
publicXxServlet xxServlet(){
return newXxServlet();
}
@Bean
publicYyFilter yyFilter(){
return newYyFilter();
}
@Bean
publicZzListener zzListener(){
return newZzListener();
}
(2)通过RegistrationBean
@Bean
publicServletRegistrationBean servletRegistrationBean(){
return newServletRegistrationBean(newXxServlet(),"/xx/*");
}
@Bean
publicFilterRegistrationBean filterRegistrationBean(){
FilterRegistrationBean registrationBean=newFilterRegistrationBean();
registrationBean.setFilter(newYyFilter());
registrationBean.setOrder(2);
returnregistrationBean;
}
@Bean
publicServletListenerRegistrationBean<ZzListener> zzListenerServletListenerRegistrationBean(){
return newServletListenerRegistrationBean<ZzListener>(newZzListener())
}

相关文章:

  • 2021-04-15
  • 2021-12-02
  • 2022-12-23
  • 2021-04-04
  • 2021-12-28
猜你喜欢
  • 2021-05-17
  • 2021-10-10
  • 2022-12-23
  • 2021-04-16
  • 2021-05-02
  • 2021-06-10
  • 2021-08-24
相关资源
相似解决方案