### Install and Start Tomcat on Linux/Unix Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/02.JavaEE/02.服务器/01.Tomcat/01.Tomcat快速入门.md This snippet provides the necessary bash commands to download, extract, and start Apache Tomcat version 8.5.24 on Linux or Unix systems. It assumes that JDK 7 or higher is already installed on the system, which is a prerequisite for running Tomcat. ```bash # 下载解压到本地 wget http://mirrors.hust.edu.cn/apache/tomcat/tomcat-8/v8.5.24/bin/apache-tomcat-8.5.24.tar.gz tar -zxf apache-tomcat-8.5.24.tar.gz # 启动 Tomcat ./apache-tomcat-8.5.24/bin/startup.sh ``` -------------------------------- ### Create a Simple Embedded Tomcat Server in Java Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/02.JavaEE/02.服务器/01.Tomcat/01.Tomcat快速入门.md Demonstrates how to programmatically start an embedded Tomcat server using the `org.apache.catalina.startup.Tomcat` class. It sets the port, context path, and deploys a web application, providing a minimal example for direct server control. ```Java import java.util.Optional; import org.apache.catalina.startup.Tomcat; public class SimpleTomcatServer { private static final int PORT = 8080; private static final String CONTEXT_PATH = "/javatool-server"; public static void main(String[] args) throws Exception { // 设定 profile Optional profile = Optional.ofNullable(System.getProperty("spring.profiles.active")); System.setProperty("spring.profiles.active", profile.orElse("develop")); Tomcat tomcat = new Tomcat(); tomcat.setPort(PORT); tomcat.getHost().setAppBase("."); tomcat.addWebapp(CONTEXT_PATH, getAbsolutePath() + "src/main/webapp"); tomcat.start(); tomcat.getServer().await(); } private static String getAbsolutePath() { String path = null; String folderPath = SimpleEmbedTomcatServer.class.getProtectionDomain().getCodeSource().getLocation().getPath() .substring(1); if (folderPath.indexOf("target") > 0) { path = folderPath.substring(0, folderPath.indexOf("target")); } return path; } } ``` -------------------------------- ### Tomcat Server.xml Basic Configuration Example Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/02.JavaEE/02.服务器/01.Tomcat/01.Tomcat快速入门.md This XML snippet provides a basic example of the `conf/server.xml` configuration file. It demonstrates the root `Server` element with its `port` and `shutdown` attributes, and a nested `Service` element, illustrating the fundamental structure for configuring a Tomcat instance. ```xml ... ``` -------------------------------- ### Example JMH Benchmark Execution Output Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/12.工具/04.测试/04.JMH.md Illustrative console output from a JMH benchmark run. It displays details such as JMH version, JVM information, warmup and measurement iteration progress, thread configuration, benchmark mode, and performance metrics for each iteration. ```Shell # JMH version: 1.22 # VM version: JDK 1.8.0_181, Java HotSpot(TM) 64-Bit Server VM, 25.181-b13 # VM invoker: C:\Program Files\Java\jdk1.8.0_181\jre\bin\java.exe # VM options: -javaagent:D:\Program Files\JetBrains\IntelliJ IDEA 2019.2.3\lib\idea_rt.jar=58635:D:\Program Files\JetBrains\IntelliJ IDEA 2019.2.3\bin -Dfile.encoding=UTF-8 # Warmup: 3 iterations, 10 s each # Measurement: 10 iterations, 5 s each # Timeout: 10 min per iteration # Threads: 8 threads, will synchronize iterations # Benchmark mode: Throughput, ops/time # Benchmark: io.github.dunwu.javatech.jmh.StringBuilderBenchmark.testStringAdd # Run progress: 0.00% complete, ETA 00:05:20 # Fork: 1 of 2 # Warmup Iteration 1: 21803.050 ops/ms # Warmup Iteration 2: 22501.860 ops/ms # Warmup Iteration 3: 20953.944 ops/ms Iteration 1: 21627.645 ops/ms Iteration 2: 21215.269 ops/ms Iteration 3: 20863.282 ops/ms Iteration 4: 21617.715 ops/ms Iteration 5: 21695.645 ops/ms Iteration 6: 21886.784 ops/ms Iteration 7: 21986.899 ops/ms Iteration 8: 22389.540 ops/ms Iteration 9: 22507.313 ops/ms Iteration 10: 22124.133 ops/ms # Run progress: 25.00% complete, ETA 00:04:02 # Fork: 2 of 2 # Warmup Iteration 1: 22262.108 ops/ms # Warmup Iteration 2: 21567.804 ops/ms ``` -------------------------------- ### Servlet init() Method Implementation Example Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/02.JavaEE/01.JavaWeb/01.JavaWeb之Servlet指南.md An example of implementing the `init()` method, which is invoked only once when the servlet is first loaded. This method is typically used for one-time initialization tasks, such as loading configuration or establishing connections. ```Java public void init() throws ServletException { // 初始化代码... } ``` -------------------------------- ### Verify Maven Installation and Version Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/11.软件/01.构建/01.Maven/01.Maven快速入门.md This command is used to confirm a successful Maven installation by displaying its version, home directory, Java version, and operating system details. ```Shell $ mvn -v Apache Maven 3.5.4 (1edded0938998edf8bf061f1ceb3cfdeccf443fe; 2018-06-18T02:33:14+08:00) Maven home: /opt/maven/apache-maven-3.5.4 Java version: 1.8.0_191, vendor: Oracle Corporation, runtime: /mnt/disk1/jdk1.8.0_191/jre Default locale: zh_CN, platform encoding: UTF-8 OS name: "linux", version: "3.10.0-327.el7.x86_64", arch: "amd64", family: "unix" ``` -------------------------------- ### Reflections Query Methods Examples Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/12.工具/99.其他/03.Reflections.md This Java code provides a comprehensive set of examples for various query methods available in the Reflections library. It covers scanning for subtypes, annotated types, resources, methods, constructors, fields, and methods based on parameters or return types, demonstrating the library's versatility. ```Java // 子类型扫描 Set> modules = reflections.getSubTypesOf(com.google.inject.Module.class); // 类型注解扫描 Set> singletons = reflections.getTypesAnnotatedWith(javax.inject.Singleton.class); // 资源扫描 Set properties = reflections.getResources(Pattern.compile(".*\\.properties")); // 方法注解扫描 Set resources = reflections.getMethodsAnnotatedWith(javax.ws.rs.Path.class); Set injectables = reflections.getConstructorsAnnotatedWith(javax.inject.Inject.class); // 字段注解扫描 Set ids = reflections.getFieldsAnnotatedWith(javax.persistence.Id.class); // 方法参数扫描 Set someMethods = reflections.getMethodsMatchParams(long.class, int.class); Set voidMethods = reflections.getMethodsReturn(void.class); Set pathParamMethods = reflections.getMethodsWithAnyParamAnnotated(PathParam.class); // 方法参数名扫描 List parameterNames = reflections.getMethodParamNames(Method.class); // 方法使用扫描 Set usages = reflections.getMethodUsages(Method.class); ``` -------------------------------- ### View Initial Maven Project Dependencies Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/13.框架/01.Spring/01.Spring核心/31.SpringBoot之快速入门.md This Maven command displays the current dependency tree of the project. Initially, with only spring-boot-starter-parent, it shows minimal dependencies, demonstrating the need to add specific starters for functionality like web development. ```shell $ mvn dependency:tree [INFO] com.example:myproject:jar:0.0.1-SNAPSHOT ``` -------------------------------- ### Create Spring Boot Hello World Application Class Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/13.框架/01.Spring/01.Spring核心/31.SpringBoot之快速入门.md This Java code defines a simple Spring Boot application class. It uses @RestController for REST handling, @RequestMapping to map the root path to a "Hello World!" response, and @EnableAutoConfiguration for automatic Spring configuration. The main method uses SpringApplication.run to bootstrap the application. ```java @RestController @EnableAutoConfiguration public class MyApplication { @RequestMapping("/") String home() { return "Hello World!"; } public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } ``` -------------------------------- ### Run Spring Boot Application with Maven Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/13.框架/01.Spring/01.Spring核心/31.SpringBoot之快速入门.md This command executes the Spring Boot application using the Maven spring-boot:run goal. It starts the embedded web server (e.g., Tomcat) and deploys the application, making it accessible via localhost:8080. The output shows the Spring Boot banner and application startup logs. ```shell $ mvn spring-boot:run . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.6.1) ....... . . . ....... . . . (log output here) ....... . . . ........ Started MyApplication in 2.222 seconds (JVM running for 6.514) ``` -------------------------------- ### Add Spring Boot Web Starter to pom.xml Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/13.框架/01.Spring/01.Spring核心/31.SpringBoot之快速入门.md This XML snippet demonstrates how to add the spring-boot-starter-web dependency to the pom.xml file. This starter automatically pulls in all necessary dependencies for building a web application, including an embedded Tomcat server. ```xml org.springframework.boot spring-boot-starter-web ``` -------------------------------- ### Create Initial Maven pom.xml for Spring Boot Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/13.框架/01.Spring/01.Spring核心/31.SpringBoot之快速入门.md This XML snippet defines the basic structure of a Maven pom.xml file for a Spring Boot project. It includes the spring-boot-starter-parent dependency, which provides default configurations and dependency management for Spring Boot applications. ```xml 4.0.0 com.example myproject 0.0.1-SNAPSHOT org.springframework.boot spring-boot-starter-parent 2.6.1 ``` -------------------------------- ### Check Java Version for Spring Boot Project Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/13.框架/01.Spring/01.Spring核心/31.SpringBoot之快速入门.md This command checks the installed Java Development Kit (JDK) version on the system, which is a prerequisite for Spring Boot development. It displays the Java version, runtime environment, and virtual machine details. ```shell $ java -version java version "1.8.0_102" Java(TM) SE Runtime Environment (build 1.8.0_102-b14) Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode) ``` -------------------------------- ### Check Maven Version for Spring Boot Project Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/13.框架/01.Spring/01.Spring核心/31.SpringBoot之快速入门.md This command verifies the installed Apache Maven version, essential for building Spring Boot projects. It outputs the Maven version, home directory, and the Java version it's using. ```shell $ mvn -v Apache Maven 3.5.4 (1edded0938998edf8bf061f1ceb3cfdeccf443fe; 2018-06-17T14:33:14-04:00) Maven home: /usr/local/Cellar/maven/3.3.9/libexec Java version: 1.8.0_102, vendor: Oracle Corporation ``` -------------------------------- ### Implement Query by Example for User Entity Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/13.框架/01.Spring/02.Spring数据/04.Spring之JPA.md Provides a concrete example of how to use Query by Example to find users. It demonstrates creating an `Example` object from a `User` entity with specific criteria (name and department ID). ```java public List getByExample(String name) { Department dept = new Department(); dept.setId(1); User user = new User(); user.setName(name); user.setDepartment(dept); Example example = Example.of(user); List list = userDao.findAll(example); return list } ``` -------------------------------- ### Thumbnailator Image Resizing Examples Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/12.工具/99.其他/06.Thumbnailator.md Demonstrates how to resize images using Thumbnailator, showing examples of setting exact dimensions with `size` and scaling by a factor or different factors for width and height using `scale`. ```Java Thumbnails.of("oldFile.png") .size(16, 16) .toFile("newFile_16_16.png"); Thumbnails.of("oldFile.png") .scale(2.0) .toFile("newFile_scale_2.0.png"); Thumbnails.of("oldFile.png") .scale(1.0, 0.5) .toFile("newFile_scale_1.0_0.5.png"); ``` -------------------------------- ### Simple JSP Hello World Example Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/02.JavaEE/01.JavaWeb/02.JavaWeb之Jsp指南.md A complete JSP example demonstrating how to display 'Hello World' and the client's IP address using an embedded Java scriptlet (`out.println` and `request.getRemoteAddr()`) within an HTML structure. ```JSP Hello World Hello World!
<% out.println("Your IP address is " + request.getRemoteAddr()); %> ``` -------------------------------- ### Create JavaMail Session Instance Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/12.工具/99.其他/04.JavaMail.md Illustrates how to create a `javax.mail.Session` instance using a `Properties` object. The session acts as the central point for managing mail operations and configurations. ```Java Properties props = new Properties(); props.setProperty("mail.transport.protocol", "smtp"); Session session = Session.getInstance(props); ``` -------------------------------- ### Ehcache Basic Usage Example in Java Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/14.中间件/02.缓存/04.Ehcache.md This Java example demonstrates how Ehcache automatically loads `ehcache.xml` from the classpath. It shows creating a `CacheManager`, getting a named cache ('helloworld'), creating an `Element` with a key-value pair, putting it into the cache, and then retrieving and printing its value. ```Java public class EhcacheDemo { public static void main(String[] args) throws Exception { // Create a cache manager final CacheManager cacheManager = new CacheManager(); // create the cache called "helloworld" final Cache cache = cacheManager.getCache("helloworld"); // create a key to map the data to final String key = "greeting"; // Create a data element final Element putGreeting = new Element(key, "Hello, World!"); // Put the element into the data store cache.put(putGreeting); // Retrieve the data element final Element getGreeting = cache.get(key); // Print the value System.out.println(getGreeting.getObjectValue()); } } ``` -------------------------------- ### Instantiating Spring IoC Containers with ApplicationContext Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/13.框架/01.Spring/01.Spring核心/02.SpringIoC.md Demonstrates how to create instances of Spring's IoC container using ClassPathXmlApplicationContext and FileSystemXmlApplicationContext to load configuration from different sources. These examples show the basic setup for a Spring application context. ```Java BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath.xml"); ``` ```Java BeanFactory beanFactory = new FileSystemXmlApplicationContext("fileSystemConfig.xml"); ``` -------------------------------- ### Verify Java Development Kit (JDK) Installation Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/11.软件/01.构建/01.Maven/01.Maven快速入门.md This command checks the installed Java Development Kit (JDK) version, which is a prerequisite for running Maven. It displays the Java version, runtime environment, and virtual machine details. ```Shell $ java -version java version "1.8.0_191" Java(TM) SE Runtime Environment (build 1.8.0_191-b12) Java HotSpot(TM) 64-Bit Server VM (build 25.191-b12, mixed mode) ``` -------------------------------- ### Customize Query by Example with ExampleMatcher Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/13.框架/01.Spring/02.Spring数据/04.Spring之JPA.md Shows how to use `ExampleMatcher` to define more flexible query conditions for Query by Example, such as `startsWith` and `ignoreCase` for property matching. ```java ExampleMatcher matcher = ExampleMatcher.matching().withMatcher("xxx", GenericPropertyMatchers.startsWith().ignoreCase()); Example example = Example.of(user, matcher); ``` -------------------------------- ### Manage Nexus Service Operations Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/11.软件/01.构建/01.Maven/05.Maven教程之发布jar到私服或中央仓库.md This snippet demonstrates how to use the `nexus` executable script to manage the Nexus service. It shows the available commands for starting, stopping, running, and checking the status of the Nexus server, providing essential administrative control. ```bash $ ./nexus Usage: ./nexus {start|stop|run|run-redirect|status|restart|force-reload} ``` ```bash ./nexus start ``` ```bash ./nexus stop ``` -------------------------------- ### Build JMH Benchmark Project with Maven Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/12.工具/04.测试/04.JMH.md Command-line instructions to navigate into the project directory and build the JMH benchmark project using Maven. This compiles the source code and packages it, typically into an executable JAR. ```Shell cd test/ mvn clean install ``` -------------------------------- ### Example JMH Benchmark for String vs. StringBuilder Performance Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/12.工具/04.测试/04.JMH.md Demonstrates how to write a JMH microbenchmark in Java to compare the performance of `String` concatenation using the `+` operator versus `StringBuilder.append()` for building strings in a loop. It utilizes JMH annotations for benchmark mode, warmup, measurement iterations, thread count, and forks, along with a `main` method to execute the benchmark. ```Java import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.runner.*; import java.util.concurrent.TimeUnit; @BenchmarkMode(Mode.Throughput) @Warmup(iterations = 3) @Measurement(iterations = 10, time = 5, timeUnit = TimeUnit.SECONDS) @Threads(8) @Fork(2) @OutputTimeUnit(TimeUnit.MILLISECONDS) public class StringBuilderBenchmark { @Benchmark public void testStringAdd() { String a = ""; for (int i = 0; i < 10; i++) { a += i; } // System.out.println(a); } @Benchmark public void testStringBuilderAdd() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 10; i++) { sb.append(i); } // System.out.println(sb.toString()); } public static void main(String[] args) throws RunnerException { Options options = new OptionsBuilder() .include(StringBuilderBenchmark.class.getSimpleName()) .output("d:/Benchmark.log") .build(); new Runner(options).run(); } } ``` -------------------------------- ### Query by Example: JpaRepository findAll Methods Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/13.框架/01.Spring/02.Spring数据/04.Spring之JPA.md Illustrates the `findAll` methods in `JpaRepository` that accept an `Example` object for querying. This allows constructing queries based on an entity instance. ```java List findAll(Example var1); List findAll(Example var1, Sort var2); ``` -------------------------------- ### Spring Dependency Injection Methods and Configuration Examples Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/13.框架/01.Spring/01.Spring核心/04.Spring依赖注入.md This section illustrates the various common ways to perform dependency injection in Spring, providing examples of the configuration metadata required for each method, including XML and Java annotation-based approaches. ```APIDOC Dependency Injection Methods and Configuration Examples: - Setter Method Injection: Configuration Example: - Constructor Injection: Configuration Example: - Field Injection: Configuration Example: @Autowired User user; - Method Injection: Configuration Example: @Autowired public void user(User user) { ... } - Interface Callback Injection: Configuration Example: class MyBean implements BeanFactoryAware { ... } ``` -------------------------------- ### Initialize JMH Project with Maven Archetype Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/12.工具/04.测试/04.JMH.md Command-line instructions to initialize a new JMH benchmarking project using a Maven archetype. This sets up the basic project structure, group ID, artifact ID, and version for microbenchmarks. ```Shell $ mvn archetype:generate \ -DinteractiveMode=false \ -DarchetypeGroupId=org.openjdk.jmh \ -DarchetypeArtifactId=jmh-java-benchmark-archetype \ -DgroupId=org.sample \ -DartifactId=test \ -Dversion=1.0 ``` -------------------------------- ### Run Compiled JMH Benchmark JAR Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/12.工具/04.测试/04.JMH.md Command-line instruction to execute the compiled JMH benchmark directly from its JAR file. This initiates the performance tests configured within the benchmark project. ```Shell java -jar target/benchmarks.jar ``` -------------------------------- ### Create JavaMail MimeMessage Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/12.工具/99.其他/04.JavaMail.md Shows how to instantiate a `javax.mail.internet.MimeMessage` object, which represents an email message. The `Session` object is passed to its constructor to associate the message with a mail session. ```Java MimeMessage message = new MimeMessage(session); ``` -------------------------------- ### EventPublishingRunListener `starting()` Method Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/13.框架/01.Spring/00.Spring综合/21.SpringBoot知识图谱.md This method, part of the `EventPublishingRunListener` implementation, is responsible for publishing the `ApplicationStartedEvent`. This event signals that the application has begun its startup process, allowing any registered `ApplicationListener` instances to react accordingly. ```Java public void starting() { // 发布一个ApplicationStartedEvent this.initialMulticaster.multicastEvent(new ApplicationStartedEvent(this.application, this.args)); } ``` -------------------------------- ### Loading Document from File Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/12.工具/99.其他/05.Jsoup.md Explains how to parse an HTML file from the local filesystem into a Jsoup Document. It covers specifying the character set and a base URI for resolving relative paths within the file. ```Java File input = new File("/tmp/input.html"); Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/"); ``` -------------------------------- ### Log4j XML Configuration Example Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/12.工具/99.其他/01.Java日志.md This Log4j configuration provides an example of setting up a console appender with a level range filter and a daily rolling file appender. It also illustrates how to define custom loggers for specific packages, control additivity, and configure the root logger with different logging levels and appender references. ```XML ``` -------------------------------- ### Spring Caching: Basic Usage Example with @Cacheable, @CachePut, @CacheEvict Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/14.中间件/02.缓存/04.Ehcache.md Provides a comprehensive Java example demonstrating the practical application of `@Cacheable`, `@CachePut`, and `@CacheEvict` annotations within a `UserService`. It shows how to cache method results, update cached data, and remove entries, including conditional caching and full cache clearing. ```java @Service public class UserService { // @Cacheable可以设置多个缓存,形式如:@Cacheable({"books", "isbns"}) @Cacheable(value={"users"}, key="#user.id") public User findUser(User user) { return findUserInDB(user.getId()); } @Cacheable(value = "users", condition = "#user.getId() <= 2") public User findUserInLimit(User user) { return findUserInDB(user.getId()); } @CachePut(value = "users", key = "#user.getId()") public void updateUser(User user) { updateUserInDB(user); } @CacheEvict(value = "users") public void removeUser(User user) { removeUserInDB(user.getId()); } @CacheEvict(value = "users", allEntries = true) public void clear() { removeAllInDB(); } } ``` -------------------------------- ### JSP Include Example - main.jsp Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/02.JavaEE/01.JavaWeb/02.JavaWeb之Jsp指南.md A main JSP file (`main.jsp`) demonstrating the usage of the `jsp:include` action to dynamically insert content from `date.jsp`. ```JSP <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 菜鸟教程(runoob.com)

include 动作实例

``` -------------------------------- ### JavaMail Store Class API Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/12.工具/99.其他/04.JavaMail.md Describes the `javax.mail.Store` class, used for retrieving and storing email messages. It outlines methods for obtaining a store instance, connecting to the mail server, accessing mail folders, and closing the connection. ```APIDOC Class: javax.mail.Store Purpose: Handles receiving and storing email messages. Methods: getStore(): Description: Creates a Store object. Multiple overloaded methods available in Session class. connect(username: String, password: String): Description: Connects to the mail server. Required if 'mail.smtp.auth' is true. getFolder(folderName: String): Description: Retrieves a Folder object representing a mail folder within the mailbox. close(): Description: Closes the connection to the mail server. ``` -------------------------------- ### Add Maven Dependency for Embedded Tomcat Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/02.JavaEE/02.服务器/01.Tomcat/01.Tomcat快速入门.md Adds the `tomcat-embed-core` dependency to `pom.xml` for embedding Tomcat directly into a Java application. This allows programmatic control over the server lifecycle. ```XML org.apache.tomcat.embed tomcat-embed-core 8.5.24 ``` -------------------------------- ### Create JavaMail InternetAddress Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/12.工具/99.其他/04.JavaMail.md Demonstrates how to create an `javax.mail.internet.InternetAddress` object, which represents an email address. This class is used to specify senders and recipients for mail messages. ```Java Address address = new InternetAddress("[email protected]"); ``` -------------------------------- ### JMH API Annotations Reference Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/12.工具/04.测试/04.JMH.md This section provides a reference for commonly used annotations in the Java Microbenchmark Harness (JMH) framework. Each entry explains the purpose, parameters, and usage of a specific JMH annotation for configuring benchmarks. ```APIDOC @BenchmarkMode Description: Specifies the type of benchmark to perform. Types: - Throughput: Measures overall throughput (operations per unit time). - AverageTime: Measures the average time per operation. - SampleTime: Collects random samples and outputs their distribution. - SingleShotTime: Runs the benchmark only once, often for cold-start performance. - All: Runs the benchmark in all available modes. ``` ```APIDOC @Warmup Description: Configures the warmup phase before actual measurements begin. This is crucial for accurate benchmarking due to JVM's JIT compilation, ensuring the code is optimized before performance is recorded. Parameters: - iterations: The number of warmup iterations. ``` ```APIDOC @Measurement Description: Defines the parameters for the measurement phase of the benchmark. Parameters: - iterations: The number of measurement rounds. - time: The duration of each measurement round. - timeUnit: The time unit for the duration (e.g., seconds, milliseconds). ``` ```APIDOC @Threads Description: Sets the number of threads to use for the benchmark within each process. This allows for testing concurrent performance characteristics. ``` ```APIDOC @Fork Description: Determines how many separate JVM processes (forks) JMH should create to run the benchmark. Each fork runs the benchmark independently, which can help isolate results and ensure consistency. ``` ```APIDOC @OutputTimeUnit Description: Defines the time unit for the benchmark results, such as seconds, milliseconds, or microseconds, for clearer and more appropriate reporting. ``` ```APIDOC @Benchmark Description: A method-level annotation that marks a method as a benchmark target, indicating that JMH should execute and measure its performance. Its usage is similar to JUnit's @Test annotation. ``` ```APIDOC @Param Description: A property-level annotation that can be used to specify multiple values for a particular parameter. This is especially useful for testing a function's performance under different input conditions without writing separate benchmarks for each case. ``` ```APIDOC @Setup Description: A method-level annotation indicating that the annotated method should be executed once before the benchmark runs. It is typically used for initialization tasks, such as setting up data or resources required by the benchmark. ``` ```APIDOC @TearDown Description: A method-level annotation indicating that the annotated method should be executed once after the benchmark completes. It is primarily used for cleanup tasks, such as closing thread pools, database connections, or releasing other resources. ``` ```APIDOC @State Description: Declares that a class is a 'state' object for the benchmark, allowing JMH to inject instances of this class into benchmark methods. It requires a Scope parameter to define the sharing scope of the state. Scopes: - Thread: The state instance is unique to each benchmark thread. - Group: The state instance is shared by all threads within the same benchmark group. - Benchmark: The state instance is shared across all threads and forks of the benchmark. ``` -------------------------------- ### Add JMH Maven Dependencies Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/12.工具/04.测试/04.JMH.md Provides the necessary Maven dependencies for integrating JMH (Java Microbenchmark Harness) into a Java project. It includes `jmh-core` for the core framework and `jmh-generator-annprocess` for annotation processing, with `provided` scope for the latter. ```Maven org.openjdk.jmh jmh-core ${jmh.version} org.openjdk.jmh jmh-generator-annprocess ${jmh.version} provided ``` -------------------------------- ### Loading Document from HTML String Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/12.工具/99.其他/05.Jsoup.md Demonstrates how to parse a complete HTML string into a Jsoup Document object using `Jsoup.parse()` methods. The `baseUri` parameter can be used to resolve relative URLs. ```Java String html = "First parse" + "

Parsed HTML into a doc.

"; Document doc = Jsoup.parse(html); ``` -------------------------------- ### Configure JavaMail Properties Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/12.工具/99.其他/04.JavaMail.md Demonstrates how to initialize a `Properties` object with common JavaMail configuration settings such as debug mode, host, transport protocol, and SMTP authentication. These properties are crucial for establishing a session with a mail server. ```Java Properties prop = new Properties(); prop.setProperty("mail.debug", "true"); prop.setProperty("mail.host", "[email protected]"); prop.setProperty("mail.transport.protocol", "smtp"); prop.setProperty("mail.smtp.auth", "true"); ``` -------------------------------- ### JUnit 5 Core Annotations Reference Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/12.工具/04.测试/01.Junit.md A reference guide to common JUnit 5 annotations, detailing their purpose, execution timing, and inheritance behavior for test classes and methods. ```APIDOC @AfterEach: Purpose: Denotes that the annotated method should be executed _after_ **each** @Test, @RepeatedTest, @ParameterizedTest, or @TestFactory method in the current class. Analogy: JUnit 4’s @After. Inheritance: Such methods are _inherited_ unless they are _overridden_. @BeforeAll: Purpose: Denotes that the annotated method should be executed _before_ **all** @Test, @RepeatedTest, @ParameterizedTest, and @TestFactory methods in the current class. Analogy: JUnit 4’s @BeforeClass. Inheritance: Such methods are _inherited_ (unless they are _hidden_ or _overridden_). Constraint: Must be `static` (unless the "per-class" test instance lifecycle is used). @AfterAll: Purpose: Denotes that the annotated method should be executed _after_ **all** @Test, @RepeatedTest, @ParameterizedTest, and @TestFactory methods in the current class. Analogy: JUnit 4’s @AfterClass. Inheritance: Such methods are _inherited_ (unless they are _hidden_ or _overridden_). Constraint: Must be `static` (unless the "per-class" test instance lifecycle is used). @Nested: Purpose: Denotes that the annotated class is a nested, non-static test class. Constraint: @BeforeAll and @AfterAll methods cannot be used directly in a @Nested test class unless the "per-class" test instance lifecycle is used. Inheritance: Such annotations are not _inherited_. @Tag: Purpose: Used to declare _tags_ for filtering tests, either at the class or method level. Analogy: Test groups in TestNG or Categories in JUnit 4. Inheritance: Such annotations are _inherited_ at the class level but not at the method level. @Disabled: Purpose: Used to _disable_ a test class or test method. Analogy: JUnit 4’s @Ignore. Inheritance: Such annotations are not _inherited_. @ExtendWith: Purpose: Used to register custom extensions. Inheritance: Such annotations are _inherited_. ``` -------------------------------- ### Loading Document from URL Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/12.工具/99.其他/05.Jsoup.md Shows how to fetch and parse an HTML document directly from a URL using `Jsoup.connect().get()`. It also demonstrates advanced connection options like adding data, setting user agents, cookies, and timeouts for POST requests. ```Java Document doc = Jsoup.connect("http://example.com/").get(); ``` ```Java Document doc = Jsoup.connect("http://example.com") .data("query", "Java") .userAgent("Mozilla") .cookie("auth", "token") .timeout(3000) .post(); ``` -------------------------------- ### Tomcat Web Project Deployment Directory Structure Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/02.JavaEE/02.服务器/01.Tomcat/01.Tomcat快速入门.md This snippet illustrates the standard directory structure for a web application deployed on Tomcat, detailing the purpose of key directories like `webapp`, `META-INF`, `WEB-INF`, `classes`, `lib`, and `web.xml` for proper application deployment and security. ```text |-- webapp # 站点根目录 |-- META-INF # META-INF 目录 | `-- MANIFEST.MF # 配置清单文件 |-- WEB-INF # WEB-INF 目录 | |-- classes # class文件目录 | | |-- *.class # 程序需要的 class 文件 | | `-- *.xml # 程序需要的 xml 文件 | |-- lib # 库文件夹 | | `-- *.jar # 程序需要的 jar 包 | `-- web.xml # Web应用程序的部署描述文件 |-- # 自定义的目录 |-- # 自定义的资源文件 ``` -------------------------------- ### JavaMail Common Properties Reference Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/12.工具/99.其他/04.JavaMail.md A reference table detailing common `java.util.Properties` keys used for configuring JavaMail sessions, including their types and descriptions. These properties control various aspects of mail sending and receiving. ```APIDOC Property: mail.debug Type: boolean Description: Debug switch. Property: mail.host Type: String Description: Specifies the default mail server for sending and receiving. Property: mail.store.protocol Type: String Description: Specifies the protocol for receiving mail. Property: mail.transport.protocol Type: String Description: Specifies the protocol for sending mail. Property: mail.debug.auth Type: boolean Description: Whether debug output includes authentication commands. Default is false. ``` -------------------------------- ### Spring Transaction Propagation: PROPAGATION_REQUIRED Examples Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/13.框架/01.Spring/02.Spring数据/03.Spring之事务.md Illustrates the PROPAGATION_REQUIRED behavior where a method must run in a transaction. If a transaction exists, it joins; otherwise, a new one is started. Examples show standalone method calls and nested calls within another transactional method, demonstrating Spring's automatic transaction management. ```java // 事务属性 PROPAGATION_REQUIRED methodA { …… methodB(); …… } ``` ```java // 事务属性 PROPAGATION_REQUIRED methodB { …… } ``` ```java main { metodB(); } ``` ```java Main { Connection con=null; try{ con = getConnection(); con.setAutoCommit(false); //方法调用 methodB(); //提交事务 con.commit(); } Catch(RuntimeException ex) { //回滚事务 con.rollback(); } finally { //释放资源 closeCon(); } } ``` ```java main{ methodA(); } ``` ```java main{ Connection con = null; try{ con = getConnection(); methodA(); con.commit(); } Catch(RuntimeException ex) { con.rollback(); } finally { closeCon(); } } ``` -------------------------------- ### Dozer Custom Converter Implementation Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/12.工具/02.JavaBean/02.Dozer.md Provides a guide on implementing custom converters in Dozer when default mapping rules are insufficient. It includes a Java example of a CustomConverter implementation and demonstrates how to register it globally and at the field level in XML. ```Java public class TestCustomConverter implements CustomConverter { public Object convert(Object destination, Object source, Class destClass, Class sourceClass) { if (source == null) { return null; } CustomDoubleObject dest = null; if (source instanceof Double) { // check to see if the object already exists if (destination == null) { dest = new CustomDoubleObject(); } else { dest = (CustomDoubleObject) destination; } dest.setTheDouble(((Double) source).doubleValue()); return dest; } else if (source instanceof CustomDoubleObject) { double sourceObj = ((CustomDoubleObject) source).getTheDouble(); return new Double(sourceObj); } else { throw new MappingException("Converter TestCustomConverter " + "used incorrectly. Arguments passed in were:" + destination + " and " + source); } } } ``` ```XML org.dozer.vo.CustomDoubleObject java.lang.Double org.dozer.vo.TestCustomConverterHashMapObject org.dozer.vo.TestCustomConverterHashMapPrimeObject ``` ```XML org.dozer.vo.SimpleObj org.dozer.vo.SimpleObjPrime2 field1 field1Prime ``` -------------------------------- ### Instantiating Reflections Object Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/12.工具/99.其他/03.Reflections.md This Java code illustrates different ways to instantiate the `Reflections` object. It shows a simple constructor call with a package name for basic scanning and a more advanced configuration using `ConfigurationBuilder` to specify URLs, scanners, and input filters for fine-grained control. ```Java //scan urls that contain 'my.package', include inputs starting with 'my.package', use the default scanners Reflections reflections = new Reflections("my.package"); //or using ConfigurationBuilder new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forPackage("my.project.prefix")) .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner().filterResultsBy(optionalFilter), ...), .filterInputsBy(new FilterBuilder().includePackage("my.project.prefix")) ...); ``` -------------------------------- ### Spring Transaction Propagation: PROPAGATION_REQUIRES_NEW Example Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/13.框架/01.Spring/02.Spring数据/03.Spring之事务.md Shows PROPAGATION_REQUIRES_NEW behavior, where a new, independent transaction is always started for the method. If an existing transaction is active, it is suspended until the new transaction completes. This ensures the method runs in its own isolated transaction. ```java //事务属性 PROPAGATION_REQUIRED methodA(){ doSomeThingA(); methodB(); doSomeThingB(); } ``` ```java //事务属性 PROPAGATION_REQUIRES_NEW methodB(){ …… } ``` ```java main(){ methodA(); } ``` ```java main(){ TransactionManager tm = null; try{ //获得一个JTA事务管理器 tm = getTransactionManager(); tm.begin();//开启一个新的事务 Transaction ts1 = tm.getTransaction(); doSomeThing(); tm.suspend();//挂起当前事务 try{ tm.begin();//重新开启第二个事务 Transaction ts2 = tm.getTransaction(); methodB(); ts2.commit();//提交第二个事务 ``` -------------------------------- ### Tomcat Core Architecture Overview Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/02.JavaEE/02.服务器/01.Tomcat/01.Tomcat快速入门.md Describes the fundamental design principles and core components of Tomcat. It highlights the two main functions: handling Socket connections and managing Servlets, which are implemented by the Connector and Container components respectively. ```APIDOC Tomcat Core Functions: - Process Socket Connections: Responsible for converting network byte streams into Request and Response objects. - Load and Manage Servlets: Handles the loading, lifecycle management, and processing of specific Request requests by Servlets. Core Components: - Connector: Manages external communication and network interactions. - Container: Handles internal processing, including Servlet management and request dispatching. ``` -------------------------------- ### Mybatis Basic Usage Example in Java Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/13.框架/11.ORM/02.Mybatis原理.md This Java program demonstrates the basic steps to use Mybatis: loading the configuration, creating a `SqlSessionFactory` (which should be a singleton), opening a `SqlSession`, and executing a `selectList` operation to retrieve `User` data. It shows how to print the retrieved user names, illustrating a complete Mybatis interaction flow. ```java public class MybatisDemo { public static void main(String[] args) throws Exception { // 1. 加载 Mybatis 配置文件,创建 SqlSessionFactory // 注:在实际的应用中,SqlSessionFactory 应该是单例 InputStream inputStream = Resources.getResourceAsStream("Mybatis/Mybatis-config.xml"); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory factory = builder.build(inputStream); // 2. 创建一个 SqlSession 实例,进行数据库操作 SqlSession sqlSession = factory.openSession(); // 3. Mapper 映射并执行 Long params = 1L; List list = sqlSession.selectList("io.github.dunwu.spring.orm.mapper.UserMapper.selectByPrimaryKey", params); for (User user : list) { System.out.println("user name: " + user.getName()); } // 输出:user name: 张三 } } ``` -------------------------------- ### Common Maven Build Command Example Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/11.软件/01.构建/01.Maven/01.Maven快速入门.md This command cleans local build artifacts, builds the Maven project, and archives the output in the local repository. The -Dmaven.test.skip=true flag skips test execution, -B runs in batch mode, and -U forces an update of snapshots and releases. ```Shell mvn clean install -Dmaven.test.skip=true -B -U ``` -------------------------------- ### Configure Maven Plugin for Tomcat 7 (Deprecated) Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/02.JavaEE/02.服务器/01.Tomcat/01.Tomcat快速入门.md Configures the `tomcat7-maven-plugin` in `pom.xml` to run Tomcat via Maven. This method is not recommended due to its outdated version (last updated 2013-11-11) and limited support for newer Tomcat versions. ```XML org.apache.tomcat.maven tomcat7-maven-plugin 2.2 8080 /${project.artifactId} UTF-8 ``` -------------------------------- ### Maven Build Lifecycle Phases Reference Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/11.软件/01.构建/01.Maven/01.Maven快速入门.md A detailed reference of Maven's standard build lifecycle phases, outlining the purpose and actions performed during each phase, from validation to deployment. ```APIDOC mvn validate: Validates the project is correct and all necessary information is available for the complete build. mvn generate-sources: Generates any source code for inclusion in the compilation process. mvn process-sources: Processes the source code, e.g., filtering values. mvn generate-resources: Generates any resources for inclusion in the package. mvn process-resources: Copies and processes the resources into the destination directory, ready for packaging. mvn compile: Compiles the project's source code. mvn process-classes: Post-processes the generated files from compilation, e.g., bytecode enhancement on Java classes. mvn generate-test-sources: Generates any test source code for inclusion in the test compilation process. mvn process-test-sources: Processes the test source code, e.g., filtering values. mvn generate-test-resources: Generates any test resources for inclusion in the test package. mvn process-test-resources: Copies and processes the test resources into the test destination directory. mvn test-compile: Compiles the test source code into the test destination directory. mvn test: Runs tests using a suitable unit testing framework. These tests should not require the code to be packaged or deployed. mvn prepare-package: Performs any operations necessary to prepare a package in anticipation of actual packaging. This would typically produce an unpacked, processed version of the package (will be implemented in Maven 2.1+). mvn package: Takes the compiled code and packages it in its distributable format, such as a JAR, WAR, or EAR. mvn pre-integration-test: Performs actions required before integration tests are run. This could involve setting up the environment for integration tests. mvn integration-test: Processes and deploys the package if necessary into an environment where integration tests can be run. mvn post-integration-test: Performs actions required after integration tests are run. This could involve cleaning up the integration test environment. mvn verify: Runs any checks to verify the package is valid and meets quality criteria. mvn install: Installs the package into the local repository, for use as a dependency in other projects locally. mvn deploy: Copies the final package to the remote repository for sharing with other developers and projects (usually in conjunction with a release). ``` -------------------------------- ### SpringFactoriesLoader Configuration Example Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/13.框架/01.Spring/00.Spring综合/21.SpringBoot知识图谱.md This snippet shows an example of the `META-INF/spring.factories` file content, specifically for `EnableAutoConfiguration`. This file is used by `SpringFactoriesLoader` to discover and load auto-configuration classes in Spring Boot. ```Properties // 来自 org.springframework.boot.autoconfigure下的META-INF/spring.factories // EnableAutoConfiguration后文会讲到,它用于开启Spring Boot自动配置功能 org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\\ org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\\ org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration\\ ``` -------------------------------- ### Execute Maven Builds and Deployments with Nexus Profile Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/11.软件/01.构建/01.Maven/05.Maven教程之发布jar到私服或中央仓库.md These bash commands demonstrate how to perform Maven build and deployment operations while activating a specific profile. The `-P zp` flag ensures that the Maven project utilizes the Nexus repository configurations defined in the `settings.xml` for dependency resolution and artifact publishing. ```bash ## 编译并打包 maven 项目 $ mvn clean package -Dmaven.skip.test=true -P zp ``` ```bash ## 编译并上传 maven 交付件(jar 包) $ mvn clean deploy -Dmaven.skip.test=true -P zp ``` -------------------------------- ### JdbcTemplate Execute DDL Example Source: https://github.com/dunwu/java-tutorial/blob/master/docs/01.Java/13.框架/01.Spring/02.Spring数据/02.Spring之JDBC.md Illustrates using `JdbcTemplate.execute()` to perform DDL operations. This example demonstrates how to drop and create a database named 'test' and then create a 'user' table within it. ```Java public void recreateTable() { jdbcTemplate.execute("DROP DATABASE IF EXISTS test"); jdbcTemplate.execute("CREATE DATABASE test"); jdbcTemplate.execute("USE test"); jdbcTemplate.execute("DROP TABLE if EXISTS user"); jdbcTemplate.execute("DROP TABLE if EXISTS user"); // @formatter:off StringBuilder sb = new StringBuilder(); sb.append("CREATE TABLE user (id int (10) unsigned NOT NULL AUTO_INCREMENT,\n") .append("name varchar (64) NOT NULL DEFAULT '',\n") .append("age tinyint (3) NOT NULL DEFAULT 0,\n") .append("PRIMARY KEY (ID));\n"); // @formatter:on jdbcTemplate.execute(sb.toString()); } ```