天天看點

SpringBoot Thymeleaf web執行個體擷取SpringBoot項目骨架SpringBoot中的SpringMVC和Thymeleaf的使用

擷取SpringBoot項目骨架

使用IDE建立Spring應用選擇依賴  或 在http://start.spring.io/ 選擇web(thymeleaf會自動包含web)技術下載下傳壓縮包,解壓,導入即可。換了maven鏡像倉庫可能找不到依賴。此時就直接用第二種方法簡單

SpringBoot中的SpringMVC和Thymeleaf的使用

說明:劃掉的與本例無關。

注意:

index.html可以被localhost:8080/直接通路 同理還有public META-NF resources下的index

修改名稱就不行,這裡Springboot預設靜态首頁index.html,并且該映射不因addViewController被重寫而覆寫

把任何頁面放入templates需要使用controller跳轉。無法直接通路,預設是templates,通過TemplatResolver bean修改

此處使用SpringMVC是以用test.html,通過controller

static檔案中的預設不會被攔截,可以直接通路,一般存放js,cs

本項目結構

SpringBoot Thymeleaf web執行個體擷取SpringBoot項目骨架SpringBoot中的SpringMVC和Thymeleaf的使用

pom 檔案

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.wisely</groupId>
	<artifactId>ch7_2</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>ch7_2</name>
	<description>Demo project for Spring Boot</description>
	<!-- 父級依賴,識别為SpringBoot項目 -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.8.BUILD-SNAPSHOT</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<!-- 輸出和源檔案編碼和jdk版本 -->
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.7</java.version>
	</properties>

	<dependencies>
		<!-- 會自動包含web -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<!-- 測試環境不被釋出 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
	<!-- 正式版無需以下 -->
	<repositories>
		<repository>
			<id>spring-snapshots</id>
			<name>Spring Snapshots</name>
			<url>https://repo.spring.io/snapshot</url>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</repository>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>

	<pluginRepositories>
		<pluginRepository>
			<id>spring-snapshots</id>
			<name>Spring Snapshots</name>
			<url>https://repo.spring.io/snapshot</url>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</pluginRepository>
		<pluginRepository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</pluginRepository>
	</pluginRepositories>


</project>
           

本項目使用的javabean  

package com.wisely.ch7_2.javabean;

/**
 * javabean
 * 
 * @author 夢境迷離
 * 
 */
public class Person {

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public Person() {
		super();
	}

	public Person(String name, Integer age) {
		super();
		this.name = name;
		this.age = age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	private String name;
	private Integer age;

}
           

頁面

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<!-- 必須放在前面 -->
	<meta content="text/html;charset=UTF-8" />
	<meta http-equiv="X-UA_Compatible" content="IE=edge" />
	<meta name="viewport" content="width=device-width,initial-scale=1" />
	
	<title>index.html</title>
	<!-- thymeleaf引用樣式 -->
	<link th:href="@{bootstrap/css/bootstrap.min.css}" target="_blank" rel="external nofollow"  rel="stylesheet" />
	<link th:href="@{bootstrap/css/bootstrap-theme.min.css}" target="_blank" rel="external nofollow"  rel="stylesheet" />

</head>

<body>

	<div class="panel panel-primary">
		<div class="panel-heading">
			<h3 class="panel-title">通路model</h3>
		</div>
		<div class="panel-body">
			<span th:text="${singlePerson.name}"></span>
		</div>
	</div>

	<div th:if="${not #lists.isEmpty(people)}">
		<div class="panel panel-primary">
			<div class="panel-heading">
				<h3 class="panel-title">清單</h3>
			</div>
			<div class="panel-body">
				<ul class="list-group">
					<li class="list-group-item" th:each="person:${people}"><span
						th:text="${person.name}"></span> <span th:text="${person.age}"></span>
						<button class="btn"
							th:οnclick="'getName(\'' + ${person.name} + '\');'">獲得名字</button>
					</li>
				</ul>
			</div>
		</div>
	</div>
	<!-- thymeleaf引入js  -->
	<script th:src="@{jquery-2.0.0.min.js}" type="text/javascript"></script>
	<script th:src="@{bootstrap/js/bootstrap.min.js}"></script>
	<script th:inline="javascript">
	var single = [[${singlePerson}]];
	console.log(single.name+"/"+single.age);
	function getName(name) {
		console.log(name);
	}
	</script>
</body>
</html>
           

控制器和配置

說明:https配置部分可以忽略,因為要生成SSL與springmvc無關,,注釋掉即可

package com.wisely.ch7_2;

import java.util.ArrayList;
import java.util.List;
import com.wisely.ch7_2.javabean.Person;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

// 這裡啟動類裡面放了控制器與配置資訊,僅僅是為了友善,希望不要效仿。
@Controller
@SpringBootApplication
public class Ch72Application extends WebMvcConfigurerAdapter {

	public static void main(String[] args) {
		SpringApplication.run(Ch72Application.class, args);
	}

	 @RequestMapping("/")
	 public String inde(Model model) {
	 Person single = new Person("aa",11);
	
	 List<Person> people = new ArrayList<Person>();
	
	 Person person1 = new Person("張三",11);
	 Person person2 = new Person("李四",22);
	 Person person3 = new Person("王五",33);
	 people.add(person1);
	 people.add(person2);
	 people.add(person3);
	
	 model.addAttribute("singlePerson",single);
	 model.addAttribute("people",people);
	
	 return "test";
	
	 }
	/**
	 * 特點的伺服器配置,tomcat
	 * 
	 * @return
	 */
	@Bean
	public EmbeddedServletContainerFactory servletContainer() {
		TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
			/**
			 * 重寫postProcessContext方法
			 */
			@Override
			protected void postProcessContext(Context context) {
				SecurityConstraint securityConstraint = new SecurityConstraint();
				securityConstraint.setUserConstraint("CONFINDENTIAL");
				SecurityCollection collection = new SecurityCollection();
				collection.addPattern("/*");
				securityConstraint.addCollection(collection);
				context.addConstraint(securityConstraint);

			}

		};
		// 添加tomcat的connector
		tomcat.addAdditionalTomcatConnectors(httpConnector());
		return tomcat;
	}

	/**
	 * 将http強制重定向至https
	 * 
	 * @return
	 */
	@Bean
	public Connector httpConnector() {

		Connector connector = new Connector(
				"org.apache.coyote.http11.Http11NioProtocol");
		connector.setScheme("http");
		connector.setPort(8080);
		connector.setSecure(false);
		connector.setRedirectPort(8443);// 重定向端口 https
		return connector;
	}
}
           

注意:

如果需要更改預設的視圖引擎 伺服器,需要繼承WebMvcConfigurerAdapter。如果需要完全控制MVC的配置,則在@Configuration注解的類上加@EnableWebMvc。這裡thymeleaf是使用預設的自動配置

application.properies配置

說明:主要是SSL配置,還沒有學到或者看不懂可以忽略,不影響使用Thyemeleaf。使用https,則無論輸入http://localhost:8080還是https://localhost:8443都可以通路,前者被強轉定向到https.

內建Thymeleaf3.0

如果報錯标簽沒有閉合可以添加屬性配置或者使用thymeleaf3.0【添加pom的紅色部分】

<properties>
<thymeleaf.version>3.0.0.RELEASE</thymeleaf.version>
	<thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.7</java.version>
</properties>
           

當然也可以繼續使用Thymeleaf2.x,但是需要配置

#解析非嚴格的html5

spring.thymeleaf.mode=LEGACYHTML5

并增加依賴

<dependency>
	 <groupId>net.sourceforge.nekohtml</groupId>
	<artifactId>nekohtml</artifactId>
	<version>1.9.22</version>
  </dependency>
           
#以下都是預設配置
#server.port=80
##機關是秒,預設是30分鐘
#server.session-timeout=30*60
#通路路徑
#server.context-path=/ 
#tomcat編碼
#server.tomcat.uri-encoding=utf-8
#是否開啟tomcat壓縮
#server.tomcat.compression=off 
server.port = 8443
           

下面都是https配置,上面沒有配置,則下面不需要加上

server.ssl.key-store = .keystore https證書的檔案 classpath下
server.ssl.key-store-password = https證書密碼
server.ssl.keyStoreType = JKS 密鑰類型
server.ssl.keyAlias: tomcat 證書别名
           

調試/啟動項目

SPringBoot可以使用maven啟動  或者以普通java程式啟動 【tomcat當然可以】

可以添加debug=true  檢視自動配置的相信資訊。

SpringBoot Thymeleaf web執行個體擷取SpringBoot項目骨架SpringBoot中的SpringMVC和Thymeleaf的使用

觀察控制台自動配置資訊

@SpringBootApplication相當與組合了 自動配置注解與自動掃描注解

即@SpringBootApplication注解等價于以預設屬性使用@Configuration,@EnableAutoConfiguration和@ComponentScan:

控制台列印出許多自動配置的資訊均是由組合注解@SpringBootApplication來完成 。

SpringBoot Thymeleaf web執行個體擷取SpringBoot項目骨架SpringBoot中的SpringMVC和Thymeleaf的使用

通路https://localhost:8443/ 【沒有配置https的8080】

SpringBoot Thymeleaf web執行個體擷取SpringBoot項目骨架SpringBoot中的SpringMVC和Thymeleaf的使用

下面這個紅色應該是浏覽器問題。不影響。

參考 JavaEE開發的颠覆者: Spring Boot實戰、SpringBoot文檔,Break易站 http://www.breakyizhan.com/springboot/3096.html

改于2018年5月3日

繼續閱讀