Spring boot开发web项目,通常打成jar包,使用内置的web服务器 Tomcat、Jetty、undertow 来运行。静态资源(css、js、图片等)默认放在resources/static下面。如果要修改默认存放目录,可以通过设置属性 spring.mvc.static-path-pattern来实现。
模板文件默认放在 templates目录下。Spring boot支持使用模板来开发web应用,支持的模板类型包括:
- FreeMarker
- Groovy
- Thymeleaf
- Mustache
Spring boot不建议使用jsp开发web。本文使用Thymeleaf来作为模板引擎开发web项目。
Thymeleaf
Thymeleaf是一个Java模板引擎开发库,可以处理和生成HTML、XML、JavaScript、CSS和文本,在Web和非Web环境下都可以正常工作。Thymeleaf可以跟Spring boot很好的集成。
项目结构
几个重要文件整理如下:
JsoupApplication.java
package com.example.jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@EnableAutoConfiguration(exclude=DataSourceAutoConfiguration.class)
@ComponentScan(basePackages= {"com.example.jsoup.*"})
public class JsoupApplication extends SpringBootServletInitializer{
public static Logger logger = LoggerFactory.getLogger(JsoupApplication.class);
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
logger.info("《使用外部tomcat配置启动springboot》");
application.sources(this.getClass());
return super.configure(application);
}
public static void main(String[] args) {
SpringApplication.run(JsoupApplication.class, args);
logger.info("*****************");
logger.info("与Jsoup整合springboot_thymeleaf启动完成!!");
logger.info("*****************");
}
}
pom.xml
<?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.example</groupId>
<artifactId>springboot_thymeleaf</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>springboot_thymeleaf</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--热启动 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<!-- jsoup html解析器 -->
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.11.3</version>
</dependency>
<!-- thymeleaf依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<!--热启动 -->
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
</project>
indexController.java
package com.example.jsoup.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping(value="")
public class IndexController {
Logger logger = LoggerFactory.getLogger(this.getClass());
@GetMapping(produces = "text/plain;charset=utf-8")
public String index(ModelMap model) {
logger.info("《jsoup,thymeleaf与springBoot简单整合》---->《首页》");
model.addAttribute("name", "thymeleaf");
return "index";
}
}
JsoupController.java
package com.example.jsoup.controller;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 参考网址
* http://www.open-open.com/jsoup/working-with-urls.htm
* @author cjy
*
*/
@RestController
@RequestMapping("Jsoup")
public class JsoupController {
Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* 解析html片段
* @return
*/
@GetMapping("/parseHtml")
public String parseHtml() {
String html = "<html><head><title>First parse</title></head>"
+ "<body><p>Parsed HTML into a doc.</p></body></html>";
Document doc = Jsoup.parse(html);
return doc.childNodes().toString();
}
/**
* 解析html文件
* @return
*/
@GetMapping("/parsePage")
public String parseWebPage() {
try {
///F:\Program Files\IDE\eclipse\workspace\jsoup/src/main/webapp/WEB-INF/views/test/jsoup.html
File input = new File("F:\\Program Files\\IDE\\eclipse\\workspace\\jsoup/src/main/webapp/WEB-INF/views/test/jsoup.html");
Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");
Element content = doc.getElementById("content");
Elements links = content.getElementsByTag("a");
logger.info("linkHref,linkText:");
for (Element link : links) {
String linkHref = link.attr("href");
String linkText = link.text();
logger.info(linkHref+","+linkText);
}
return "Parse successfully!";
} catch (IOException e) {
e.printStackTrace();
}
return "Parse fail!";
}
/**
* //解析一个body片断
* @return
*/
@GetMapping("/parseBody")
public String parseBody() {
String html = "<div><p>Lorem ipsum.</p>";
Document doc = Jsoup.parseBodyFragment(html);
Element body = doc.body();
return body.childNodes().toString();
}
/**
* 从一个URL加载一个Document
* @param url 加载的地址
*/
@GetMapping("/getByUrl")
public String getByURL(String url) {
Document doc;
String title = null;
try {
doc = Jsoup.connect(url).get();
title = doc.title();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return title;
}
}
application.properties
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
index.html
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" 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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="/static/js/jquery-2.0.3.min.js"></script>
<body>
<p th:text="'Hello, ' + ${name}" /><br/>
<span id="state"></span>
<script type="text/javascript">
$.ajax({
url:"/Jsoup/parseHtml",
type:"GET",
success:function(data){
$("#state").text(data);
console.log(data);
},
error:function(){
$("#state").text("error!");
console.log("error!");
}
})
</script>
</body>
</html>