Maven、XML和JSON
Maven
Maven是一个Java项目管理和构建的工具
Maven使用pom.xml定义项目内容,并使用预设的目录结构
在Maven中声明一个依赖项可以自动下载并导入classpath
Maven使用 groupId、artifactId 和 version唯一定位一个jar包
<?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.yw</groupId>
<artifactId>hello</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>hello</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
依赖管理
Maven通过解析依赖关系确定项目所需的jar包,Maven库查询:
https://mvnrepository.com/,Maven中央仓库:http://repo1.maven.org
Maven的依赖关系:
scope | 说明 | 实例 |
---|---|---|
compile | 编译时需要用到该jar包 | commons-logging |
test | 编译test时需要用到该jar包 | junit |
runtime | 编译时不需要,但运行时需要用到 | log4j |
provided | 编译时需要用到,但运行时由JDK或某个服务器提供 | servlet-api |
Maven从中央仓库下载所需jar包并缓存在本地
可以通过镜像加速下载 aliyun 镜像仓库配置:
<settings>
<mirrors>
<mirror>
<id>aliyun</id>
<name>aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
<mirrorOf>central</mirrorOf>
</mirror>
</mirrors>
</settings>
构建流程
理解Maven的概念:Lifecycle(生命周期),Phase(阶段)和Goal:
使用Maven构建项目就是执行Lifecycle
执行Lifecycle就是按顺序执行一系列Phase
每执行一个Phase,都会执行该Phase绑定的若干个Goal
Goal是最小执行任务单元
常用命令:
mvn clean compile
mvn test package
mvn clean package(不会打包依赖的jar)
java -cp ./hello-0.0.1-SNAPSHOT.jar com.yw.hello.App
使用插件
Maven通过自定义插件可以执行项目构建时需要的额外的功能,在pom.xml中声明插件及配置,插件会在某个Phase被执行,插件的配置和用法需参考插件官方文档
Maven常用标准插件
插件名称 | 对应执行的Phase |
---|---|
clean | clean |
complier | compile |
surefire | test |
jar | package |
常用插件:
maven-shade-plugin:打包所有依赖包并生成可执行jar
cobertura-maven-plugin:生成单元测试覆盖率报告
findbugs-maven-plugin:对Java源码进行静态分析以找出潜在问题
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.yw.hello.App</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
模块管理
Maven支持模块化管理,可以把一个大项目拆成一个模块
可以通过继承在parent的pom.xml统一定义重复配置
可以通过<modules>编译多个模块
XML和JSON
XML
XML是可扩展标记语言(eXtensible Markup Language),纯文本数据,默认使用UTF-8编码,用于表示复杂的结构化数据,用于数据的存储和传输,数据庞大,格式复杂。
XML相关技术
DTD和XSD:验证XML结构和数据是否有效
Namespace:XML节点和属性的名字空间
XSLT:把XML转化为另一种文本
XPath:一种XML节点查询语言
两种标准的解析XML的API:DOM、SAX
DOM(Document Object Model)解析
Java DOM API:将XML解析为DOM,可在内存中完整表示XML数据结构,解析速度慢,内存占用大
public class DomSample {
static final String XML_URL = "https://www.baidu.com";
public static void main(String[] args) throws Exception{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(XML_URL);
printNode(doc, 0);
}
static void printNode(Node n, int indent){
for(int i=0; i<indent; i++){
System.out.println("");
}
switch(n.getNodeType()){
case Node.DOCUMENT_NODE:
System.out.println("Document: " + n.getNodeName());
break;
case Node.ELEMENT_NODE:
System.out.println("Element: " + n.getNodeName());
break;
case Node.TEXT_NODE:
System.out.println("Text: " + n.getNodeName() + " = " + n.getNodeValue());
break;
case Node.ATTRIBUTE_NODE:
System.out.println("Attr: " + n.getNodeName() + " = " + n.getNodeValue());
break;
case Node.CDATA_SECTION_NODE:
System.out.println("CDATA: " + n.getNodeName() + " = " + n.getNodeValue());
break;
case Node.COMMENT_NODE:
System.out.println("Comment: " + n.getNodeName() + " = " + n.getNodeValue());
break;
default:
System.out.println("NodeType: " + n.getNodeType() + ", NodeName: " + n.getNodeName());
}
for(Node child = n.getFirstChild(); child != null; child = child.getNextSibling()){
printNode(child, indent + 1);
}
}
}
SAX(Simple API for XML)解析
Java SAX解析:一种流式解析XML的API,通过事件触发,速度快,调用方通过回调方法获得数据
class MyHandler extends DefaultHandler{
void print(Object... objs){
for(Object obj : objs){
System.out.print(obj);
System.out.print(" ");
}
System.out.println();
}
@Override
public void startDocument() throws SAXException{
print("start document");
}
// @Override
public void endDocumnet() throws SAXException{
print("end document");
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException{
print("start element:", localName, qName);
}
@Override
public void endElement(String uri, String localName, String qName)throws SAXException{
print("end element:", localName, qName);
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException{
print("characters:", new String(ch, start, length));
}
@Override
public void error(SAXParseException e) throws SAXException{
print("error:", e);
}
}
public class SAXSample {
static final String XML_URL = "https://www.zte.com.cn";
public static void main(String[] args) throws Exception{
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
sp.parse(XML_URL, new MyHandler());
}
}
Jackson
JSON是轻量级的数据表现方式,格式简单,解析速度快,适合Web
使用Jackson可以快速在XML和JavaBean之间互相转换,Jackson提供了读写JSON的API:实现JSON和JavaBean的互相转换,可使用Annotation定制序列化和反序列化
读取XML:
XmlMapper mapper = new XmlMapper();
Book book = mapper.readValue(xml, Book.class);
写入XML:
XmlMapper mapper = new XmlMapper();
String xml = mapper.writeValueAsString(book);
Json转JavaBean
class Book {
public String id;
public String title;
public String subtitle;
public List<String> author;
@JsonSerialize(using = CustomLocalDateSerializer.class)
@JsonDeserialize(using = CustomLocalDateDeserializer.class)
public LocalDate pubdate;
public String url;
public String price;
}
class SearchResult {
public long count;
public long total;
public List<Book> books;
}
class CustomLocalDateDeserializer extends JsonDeserializer<LocalDate> {
static DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-M-d", Locale.US);
@Override
public LocalDate deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
String s = p.getValueAsString();
if (s != null) {
try {
return LocalDate.parse(s, FORMATTER);
} catch (DateTimeException e) {
// ignore
}
}
return null;
}
}
class CustomLocalDateSerializer extends JsonSerializer<LocalDate> {
@Override
public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeString(value.toString());
}
}
public class JsonToBean {
static final String JSON_URL = "https://api.douban.com/v2/book/search?q=";
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper()
.registerModule(new JavaTimeModule());
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
false);
String json = search("java");
SearchResult result = mapper.readValue(json, SearchResult.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(result));
}
static String search(String q) {
HttpURLConnection conn = null;
StringBuilder sb = new StringBuilder(4096);
try {
URL url = new URL(JSON_URL + URLEncoder.encode(q, "UTF-8"));
conn = (HttpURLConnection) url.openConnection();
if (200 == conn.getResponseCode()) {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream(), "UTF-8"))) {
char[] buffer = new char[1024];
for (;;) {
int n = reader.read(buffer);
if (n == (-1)) {
break;
}
sb.append(buffer, 0, n);
}
}
return sb.toString();
}
throw new RuntimeException("Bad response code: "
+ conn.getResponseCode());
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
}