### Get Git Command Help Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/developer-tools/Git应用.md These commands provide detailed help and documentation for specific Git commands, explaining their usage, options, and examples directly in the command line. ```Git git help commit ``` ```Git git commit --help ``` -------------------------------- ### Java Servlet Example with @WebServlet Annotation Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/Java-Web/Servlet基础.md Demonstrates a basic Java Servlet (HiServlet) configured using the @WebServlet annotation. It specifies multiple URL patterns (/hi, /hello, *.haha) and sets loadOnStartup to 0, ensuring the Servlet is initialized when the application starts. Includes init, doPost, and doGet methods. ```Java package com.mylifes1110.java; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * value定义了多个url路径:value = {"/hi", "/hello", "*.haha"} * Servlet的创建时机设置为:loadOnStartup = 0(启动程序时创建并初始化) */ @WebServlet(name = "HiServlet", value = {"/hi", "/hello", "*.haha"}, loadOnStartup = 0) public class HiServlet extends HttpServlet { @Override public void init() throws ServletException { System.out.println("初始化方法"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("你又被访问到了!哈哈!"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } } ``` -------------------------------- ### Tomcat Directory Structure Overview Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/Server/tomact服务器基础和开发步骤.md Provides a table detailing the purpose of each main directory within a Tomcat installation, such as bin, conf, lib, webapps, and work. ```APIDOC Directory Name | Description -------------------- | ------------------------------------------------------------ bin | Stores Tomcat executable files, e.g., startup.bat (to start the service) conf | Tomcat configuration files, e.g., server.xml lib | Core JAR packages that Tomcat relies on at runtime, e.g., jsp-api.jar, servlet-api.jar logs | Stores Tomcat execution logs temp | Stores temporary files webapps | Stores deployed Web resources work | Stores Java files after JSP translation ``` -------------------------------- ### SQL Physical Pagination Examples with LIMIT Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/Java-Web/JSP.md These SQL examples illustrate how to fetch data for different pages using the `LIMIT` clause. It shows how the starting index changes for subsequent pages when retrieving 10 records per page from an `employee` table. The starting index is 0-based. ```SQL -- 第一页显示第一个10条数据(查询10条);开始索引为0 -- 从索引为0的数据开始,向后查10条数据 SELECT * FROM employee LIMIT 0 , 10; -- 第二页显示从第11条数据开始到第20条;开始索引为10 SELECT * FROM employee LIMIT 10 , 10; -- 第三页显示从第21条数据开始到第30条;开始索引为20 SELECT * FROM employee LIMIT 20 , 10; -- 第四页显示从第31条数据开始到第40条;开始索引为30 SELECT * FROM employee LIMIT 30 , 10; ``` -------------------------------- ### Example HTTP GET Request Line Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/Computer-Networks/HTTP网络协议.md Illustrates a basic HTTP GET request line, specifying the resource path and HTTP protocol version used by the client. ```HTTP GET /sample/hello.html HTTP/1.1 ``` -------------------------------- ### Complete JDBC Example for Inserting Data Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/Java-Web/JDBC数据库连接.md A comprehensive Java example demonstrating all six core JDBC steps for performing an INSERT operation. It includes loading the driver, establishing a connection, creating a statement, executing SQL, processing results, and closing resources. ```Java import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class TestInsert { public static void main(String[] args) throws ClassNotFoundException, SQLException { //1.加载驱动,将驱动字节码文件加载到JVM中 Class.forName("com.mysql.jdbc.Driver"); //2.连接数据库 String url = "jdbc:mysql://localhost:3306/companydb?useUnicode=true&characterEncoding=utf8";//数据库连接地址 String user = "root";//用户名 String password = "123456";//密码 Connection connection = DriverManager.getConnection(url, user, password); //3.获取发送SQL语句的对象 Statement statement = connection.createStatement(); //4.编写SQL语句,并执行SQL语句 String sql = "insert into user (userName, password, address, phone) values ('Ziph', '123456', '河北', '11111111111')"; int result = statement.executeUpdate(sql); //5.处理结果 if (result > 0) { System.out.println("添加成功!"); } else { System.out.println("添加失败!"); } //6.释放资源,先开后关 statement.close(); connection.close(); } } ``` -------------------------------- ### HTML Image Tag Usage Example Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/Frontend-Development/HTML和CSS基础.md Provides examples of using the `` tag with various attributes like `src`, `width`, `height`, `border`, `alt`, and `title` to display images and provide fallback/hover text. ```HTML 给你点赞的小老虎 ``` -------------------------------- ### HTTP Client Request Message Structure and Example Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/Computer-Networks/HTTP网络协议.md Illustrates the four components of an HTTP client request message: request line, headers, empty line, and request body. Includes a concrete example of a POST request. ```APIDOC POST/hello HTTP/1.1 Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 Accept-Language:zh-CN,zh;q=0.8,en-GB;q=0.6,en;q=0.4 Connection:Keep-Alive Host:localhost:8080 User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 Accept-Encoding:gzip, deflate, br username=zhangsan&age=20&add=beijing ``` -------------------------------- ### Check Git Version Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/developer-tools/Git应用.md This command is used to display the currently installed Git version on your system, confirming that Git is properly installed and accessible. ```Git git version ``` -------------------------------- ### JSP Examples for JSTL Core Tags Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/Java-Web/JSP.md Practical JSP examples demonstrating the usage of various JSTL core tags including c:set for variable assignment, c:remove for variable deletion, c:catch for exception handling, c:if for conditional logic, c:forEach for looping through collections and ranges, and c:forTokens for string tokenization. ```JSP <%@ page import="java.util.List" %> <%@ page import="java.util.ArrayList" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> JSTL标签 <%-- Set标签 向某个域中存储对象或参数 var:参数名称 scope:域名称;page、request、session、application value:参数值 --%> ${message}
<%-- reomve标签 移除某个域中的对象或参数 var:要移除的参数名称 scope:域名称 --%> ${message}
<%-- catch标签 捕获jsp页面中的异常,可用来打印堆栈跟踪信息和异常详细信息 注意:在jsp页面中捕获的异常,如果不打印任何信息,页面将忽略这个错误(没有捕获代码的任何信息和错误提示) var:异常对象名称 --%> <% //算数异常 int num = 1 / 0; %> <%--打印捕获的异常详细信息--%> ${e.message}
<%-- if标签 if条件判断 test:条件判断的条件 --%> i大于2 <%--执行1<2--%> i小于2
<%-- forEach标签 支持for循环遍历形式和增强for循环遍历形式 var:变量名 step:步长 begin:开始 end:结束 注意:在模拟for循环的时候是有局限性的,step步长必须大于0,而且begin必须小于end! items:遍历的集合或数组 varStatus:元素状态对象(varStatus属性还包含以下属性参数) current:当前元素 index:当前索引 first:是否是第一个元素 last:是否是最后一个元素 --%> <%--for循环:打印1~10--%> ${i}
<%--增强for循环:打印集合内元素--%> <% List fruits = new ArrayList<>(); fruits.add("apple"); fruits.add("banana"); fruits.add("strawberry"); request.setAttribute("fruitsName", fruits); %> <%--普通for循环--%> ${fruitsName[i]}
<%--增强for循环--%> ${j}
开始:${status.begin}
结束${status.end}
步长:${status.step}
是第几个元素:${status.count}
是否是第一个元素:${status.first}
是否是最后一个元素:${status.last}
当前索引:${status.index}
当前元素:${status.current}
<%-- forTokens标签 切割字符串 items:要分割的字符串 delims:分割字符串依据 var:分割后的元素对象 --%> <% String str = "111-222-333"; request.setAttribute("str", str); %> <%--按”-“拆分字符串str并打印分割后的字符串信息--%> ${str} ``` -------------------------------- ### MySQL Product Table Schema and Data Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/Java-Web/JSP.md SQL script to create a 'product' table with 'id', 'name', 'price', and 'count' columns, and insert sample data for demonstration purposes. This schema is used in the JSTL integration example. ```SQL use temp; create table product ( id int primary key auto_increment, name varchar(30), price double, count int ) charset = utf8; insert into product (id, name, price, count) VALUES (1, '电视机', 3000, 2); insert into product (id, name, price, count) VALUES (2, '电冰箱', 5000, 4); insert into product (id, name, price, count) VALUES (3, '空调', 10000, 1); insert into product (id, name, price, count) VALUES (4, '微波炉', 1500, 2); ``` -------------------------------- ### jQuery noConflict Method Examples Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/Frontend-Development/jQuery.md Demonstrates various ways to use jQuery's `noConflict()` method to prevent conflicts with other JavaScript frameworks that might also use the `$` shorthand. Examples show using the full `jQuery` name, assigning jQuery to a custom alias, and passing `$` as a parameter to the `ready` function. ```javascript $.noConflict(); jQuery(document).ready(function(){ jQuery("button").click(function(){ jQuery("p").text("jQuery 仍然在工作!"); }); }); ``` ```javascript var jq = $.noConflict(); jq(document).ready(function(){ jq("button").click(function(){ jq("p").text("jQuery 仍然在工作!"); }); }); ``` ```javascript $.noConflict(); jQuery(document).ready(function($){ $("button").click(function(){ $("p").text("jQuery 仍然在工作!"); }); }); ``` -------------------------------- ### Get All Request Parameter Names in Java Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/Java-Web/Servlet基础.md Demonstrates how to iterate through all request parameter names using `getParameterNames()` and then retrieve their corresponding values. Useful for dynamic parameter handling, as seen with `http://localhost:8080/reqweb/test3?username=ziph&password=123456`. ```Java Enumeration requestParameterNames = request.getParameterNames(); while (requestParameterNames.hasMoreElements()) { String parameterName = requestParameterNames.nextElement(); String parameterValue = request.getParameter(parameterName); System.out.println("name : " + parameterName + "\t" + "value : " + parameterValue); } ``` -------------------------------- ### Get Query String from GET Request URL in Java Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/Java-Web/Servlet基础.md Demonstrates how to retrieve the query string from a GET request URL. For example, from `http://localhost:8080/reqweb/test1?username=ziph&password=123456`, it extracts `username=ziph&password=123456`. This method is specific to GET requests, as POST requests typically do not have query strings. ```Java String requestQueryString = request.getQueryString(); System.out.println("请求网址后的拼接内容为:" + requestQueryString); ``` -------------------------------- ### Java: Initial Product Object Creation and Display Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/design-mode/00.设计模式基础.md This Java code snippet demonstrates the creation and display of `Product` objects without any discount logic. It sets the name and price for two different products, `iPhone` and `huaWei`, and prints their details. ```Java public class Test { public static void main(String[] args) { Product iPhone = new Product(); iPhone.setName=("iPhone11 Plus"); iPhone.setPrice=(7000.00); Product huaWei = new Product(); huaWei.setName("huaWei Mate30 Pro"); huaWei.setPrice(8000.00); System.out.println(iPhone.getName() + " 价格:" + iPhone.getPrice()); System.out.println(huaWei.getName() + " 价格:" + huaWei.getPrice()); } } ``` -------------------------------- ### Detailed Explanation of Tomcat Directories and Key Configuration Files Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/Server/tomact服务器基础和开发步骤.md Explains the function of critical Tomcat directories (bin, conf, lib, logs, temp, webapps, work) and important configuration files within the 'conf' directory (server.xml, tomcatusers.xml, web.xml, context.xml). ```APIDOC bin: Contains binary executable files. For installed versions, includes tomcat9.exe and tomcat9w.exe. For unzipped versions, includes startup.bat (to start Tomcat, requires JDK config) and shutdown.bat (to stop Tomcat). conf: A crucial directory containing four key files: - server.xml: Configures the entire server, e.g., modifying port numbers, adding virtual hosts. - tomcatusers.xml: Stores Tomcat user accounts, passwords, and roles. Users can be added based on comments in this file to access the Tomcat Manager page. - web.xml: The deployment descriptor file, registering many MIME types (document types) for client-server communication. It informs the client browser how to handle the content (e.g., text/html for HTML, triggering download for .exe). - context.xml: Provides unified configuration for all applications; usually not modified. lib: Tomcat's class library, containing numerous JAR files. Tomcat-dependent JARs can be placed here. While application-dependent JARs can also be placed here for shared access, it's generally recommended to only include Tomcat's own required JARs to ensure application portability. logs: Contains log files recording Tomcat startup and shutdown information, including exceptions if errors occur during startup. temp: Stores Tomcat's temporary files. Contents can be deleted after stopping Tomcat. webapps: The directory for web projects, where each folder represents a project. ROOT is a special project accessed when no project directory is specified in the URL (e.g., http://localhost:8080/). Other projects are accessed via their folder name (e.g., http://localhost:8080/firstweb). work: Contains files generated during runtime, which are the final executable files derived from projects in 'webapps'. This directory's contents can be deleted and will be regenerated upon next run. When a client accesses a JSP file, Tomcat generates a Java file, compiles it into a class file, and stores both in this directory. LICENSE: License file. NOTICE: Information file. ``` -------------------------------- ### Implementing a Basic Java Servlet Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/Java-Web/Servlet基础.md This code demonstrates the implementation of the `javax.servlet.Servlet` interface, overriding its five core methods: `init`, `getServletConfig`, `service`, `getServletInfo`, and `destroy`. It includes detailed comments explaining each method's purpose and shows how to output text to the console and the browser, including the current system time. The `service` method also illustrates how to set the content type for proper character encoding. ```java package com.mylifes1110.java; import javax.servlet.*; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; /** * Servlet * 实现Servlet接口中的所有方法 */ public class MyServlet implements Servlet { /** * 实例化(调用构造器,可以省略,但是要知道) */ public MyServlet() { //默认无参构造 } /** * 初始化方法 * * @param servletConfig 包含 servlet 的配置和初始化参数的 ServletConfig 对象 * @throws ServletException 如果发生妨碍 servlet 正常操作的异常 */ @Override public void init(ServletConfig servletConfig) throws ServletException { //Servlet初始化工作 } /** * 获取Servlet配置信息 * * @return 返回 ServletConfig 对象,该对象包含此 servlet 的初始化和启动参数。返回的 ServletConfig 对象是传递给 init 方法的对象。 */ @Override public ServletConfig getServletConfig() { return null; } /** * 提供服务 *

* 由 servlet 容器调用,以允许 servlet 响应某个请求。 * 此方法仅在 servlet 的 init() 方法成功完成之后调用。 * 应该为抛出或发送错误的 servlet 设置响应的状态代码。 * * @param servletRequest 包含客户端请求的 ServletRequest 对象 * @param servletResponse 包含 servlet 的响应的 ServletResponse 对象 * @throws ServletException 如果发生妨碍 servlet 正常操作的异常 * @throws IOException 果发生输入或输出异常 */ @Override public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { //请求相关内容 ServletRequest ; 相应相关内容 ServletResponse /** * 在控制台内打印输出 */ System.out.println("这是我的第一个Servlet!"); /** * 利用输出流输出系统时间,在浏览器中显示 */ PrintWriter printWriter = servletResponse.getWriter(); Date date = new Date(); printWriter.println(date); printWriter.close(); /** * 利用流输出信息在浏览器内显示 * 解决浏览器显示乱码问题 */ servletResponse.setContentType("text/html;charset=utf-8"); servletResponse.getWriter().println("这是我的第一个Servlet"); } /** * 返回有关 servlet 的信息,比如作者、版本和版权。 *

* 此方法返回的字符串应该是纯文本,不应该是任何种类的标记(比如 HTML、XML,等等)。 * * @return 包含 servlet 信息的 String */ @Override public String getServletInfo() { return null; } /** * 销毁(清除所有资源) *

* 由 servlet 容器调用,指示将从服务中取出该 servlet。 * 此方法仅在 servlet 的 service 方法已退出或者在过了超时期之后调用一次。 * 在调用此方法之后,servlet 容器不会再对此 servlet 调用 service 方法。 * 此方法为 servlet 提供了一个清除持有的所有资源(比如内存、文件句柄和线程)的机会,并确保任何持久状态都与内存中该 servlet 的当前状态保持同步。 */ @Override public void destroy() { } } ``` -------------------------------- ### Java `File` Class Basic Operations Example Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/Java-Standard-Edition/JavaIO流.md This Java code demonstrates various common operations of the `java.io.File` class, including checking file properties (read, write, execute permissions, existence), creating and deleting files, getting paths, names, sizes, and last modified times. It also shows how to get disk space information. ```Java import java.io.File; import java.io.IOException; /** * 因为有些方法之间互相影响,所以就没有注释掉! * 自己测试的时候记得注意互相影响的方法! */ public class TestFiles { public static void main(String[] args) throws IOException { File file = new File("Files\\test\\target.txt"); // File file = new File("Files\\test\\newFile"); System.out.println(file.canExecute());//所有可以打开的文件或文件夹 System.out.println(file.canWrite());//能不能修改文件 System.out.println(file.canRead());//能不能执行文件 System.out.println(file.createNewFile());//文件不存在则新建一个文件 System.out.println(file.delete());//如果文件存在,则删除,返回true file.deleteOnExit();//JVM终止时,执行删除删除文件 System.out.println(file.exists());//测试此抽象路径名表示的文件或目录是否存在 System.out.println(file.getAbsolutePath());//获得绝对路径 System.out.println(file.getPath());//获得相对路径 System.out.println(file.getName());//获得文件名(文件名.后缀) System.out.println(file.getFreeSpace() / 1024 / 1024 / 1024);//获得磁盘空闲空间容量 System.out.println(file.getTotalSpace() / 1024 / 1024 / 1024);//获得磁盘总空间容量 System.out.println(file.getParent());//指定文件的上一级目录 System.out.println(file.isDirectory());//判断是否为文件夹 System.out.println(file.isFile());//判断是否为文件 System.out.println(file.isHidden());//判断是否为隐藏文件 System.out.println((System.currentTimeMillis() - file.lastModified()) / 1000 / 60);//获取文件最后一次修改时间 System.out.println(file.length());//文件内容的字节 file.mkdirs();//创建一个新目录 } } ``` -------------------------------- ### Configure Default Welcome Pages in web.xml Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/Java-Web/Servlet基础.md Illustrates how to configure a list of default welcome files in web.xml using the tag. The server attempts to access these files in the specified order if the root path is requested. If none are found, a 404 error occurs. ```XML 欢迎.html index.html index.jsp ``` -------------------------------- ### Demonstrate HttpServlet Lifecycle in Java Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/Java-Web/Servlet基础.md This Java Servlet example illustrates the complete lifecycle of an HttpServlet. It showcases the execution order of the default constructor, init() method for initialization, doGet()/doPost() methods for handling requests, and the destroy() method for cleanup, by printing messages at each stage. ```Java package com.mylifes1110.java.servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author Ziph */ @WebServlet(name = "HttpServlet", value = "/test") public class HttpServlet extends javax.servlet.http.HttpServlet { /** * 默认无参构造器 */ public HttpServlet() { System.out.println("1.调用无参构造器"); } /** * 调用init方法进行初始化 */ @Override public void init() throws ServletException { super.init(); System.out.println("2.进行初始化工作"); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); System.out.println("3.提供服务中..."); response.getWriter().append("Servlet at:").append(request.getContextPath()); } /** * 调用destroy方法进行销毁 */ @Override public void destroy() { super.destroy(); System.out.println("4.进行销毁"); } } ``` -------------------------------- ### Payment API Request Parameters Source: https://github.com/ziphtracks/javalearningmanual/blob/master/project/小米商城/shopping/README.md Defines the required parameters for the enterprise payment interface, including price, body, order ID, and callback URL, along with their formats, examples, and whether they are mandatory. ```APIDOC Payment API Request Parameters: price: Description: 商品价格 Format: 字符串 Example: 1 Required: 是 Notes: 单位:分 body: Description: 商品标题介绍 Format: 字符串 Example: 颈椎康复指南 Required: 是 Notes: orderId: Description: 订单号 Format: 字符串 Example: dsd3sf3wsef Required: 是 Notes: 你网站的订单号 url: Description: 回调地址 Format: 字符串 Example: http://localhost:8080/abc Required: 是 Notes: 必须 http 开头 ``` -------------------------------- ### Web Application Project Structure and web.xml Configuration Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/Server/tomact服务器基础和开发步骤.md Addresses common questions regarding web application directory structure (static vs. dynamic projects), the role of the web.xml file, and how to set a default access page for a web project. ```APIDOC Question 1: What is the basic directory structure of a Web application? - Web static project: - html, js, css, images... - Web dynamic project: - html, js, css, images... - WEB-INF folder, web.xml file (core) Question 2: What content should be in the web.xml file? - The web.xml file under tomcat\webapps\ROOT package is Tomcat's page configuration. - Initially, you can copy the content of the web.xml file from tomcat\webapps\ROOT application to your own web.xml file. Question 3: How to set the default access page for a project? - In tomcat\conf\web.xml file, this file can be understood as the parent file for all web.xml files in web applications under Tomcat. - The declaration in this file specifies which files are accessed by default in a web application. If you override this content in your project's web.xml file, you can set your project's default access page. ``` -------------------------------- ### Java EnumSet.range() Example Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/Java-Standard-Edition/Java枚举.md Shows how to use `EnumSet.range()` to create an `EnumSet` that includes all enum members within a specified start and end point (e.g., `Week.MONDAY` to `Week.FRIDAY`), leveraging the ordinal order of enums. ```java //创建一个最初包含由两个指定端点所定义范围内的所有元素的枚举 set。 System.out.println(EnumSet.range(Week.MONDAY, Week.FRIDAY)); //[MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY] ``` -------------------------------- ### Overview of Tomcat Web Application Deployment Methods Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/Server/tomact服务器基础和开发步骤.md Introduces three distinct methods for deploying web applications on Tomcat: direct placement in webapps, virtual directories configured in server.xml, and virtual directories configured via context XML files in Catalina/localhost. ```APIDOC Deployment Method -------------------------------------- 1. Directly place the web application into the webapps directory 2. Virtual directory (basic version) 3. Virtual directory (optimized version) ``` -------------------------------- ### Get User-Agent Header in Java Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/Java-Web/Servlet基础.md Illustrates how to retrieve the 'User-Agent' request header, which helps identify the client's browser type and operating system. For example, it might return 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.113 Safari/537.36'. ```Java String requestHeader = request.getHeader("User-Agent"); System.out.println("User-Agent为:" + requestHeader); ``` -------------------------------- ### Java: Using OCP-Compliant Discounted Product Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/design-mode/00.设计模式基础.md This Java `main` method demonstrates the use of the `Discount` class, which adheres to the Open/Closed Principle. By instantiating `iPhone` as a `Discount` object, it applies the discount without altering the base `Product` class, showcasing how new features can be added through extension rather than modification. ```Java public class Test { public static void main(String[] args) { Product iPhone = new Discount(); iPhone.setName("iPhone11 Plus"); iPhone.setPrice(7000.00); System.out.println(iPhone.getName() + " 价格:" + iPhone.getPrice()); } } ``` -------------------------------- ### Initialize a Git Repository Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/developer-tools/Git应用.md This command initializes a new Git repository in the current directory. It creates a hidden .git folder, which serves as the version library for the project and stores all repository information. ```Git git init ``` -------------------------------- ### Reading Various Data Types with Java Scanner Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/Java-Standard-Edition/Java语言基础.md This Java example showcases the versatility of the `java.util.Scanner` class for acquiring different data types from console input. It provides commented-out examples for reading `double` (`nextDouble()`), `String` (`next()`), and `char` (`next().charAt(0)`), alongside an active example for `int` (`nextInt()`). The snippet also notes the `java.util.InputMismatchException` that can arise from type mismatches during input. ```java import java.util.Scanner;//1.引入包 public class TestScanner2{ public static void main(String[] args){ //2.声明Scanner Scanner input = new Scanner(System.in); System.out.println("请输入:"); //3.使用input的变量接收 //double result1 = input.nextDouble(); //System.out.println("值:" + result1); //4.接收字符串 //String result2 = input.next(); //System.out.println("值:" + result2); //5.接收字符 //char result3 = input.next().charAt(0); //获取一个字符串的首个字符 //System.out.println("值:" + result3); //如果输入了不普配的数据,会产生java.util.InputMismatchException异常(会有问题) int result4 = input.nextInt();//接收整数 System.out.println(result4); } } ``` -------------------------------- ### Implementing the Servlet Interface for Basic Servlet Creation Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/Java-Web/Servlet基础.md This code demonstrates the most fundamental and verbose way to create a Servlet in Java by directly implementing the `javax.servlet.Servlet` interface. It requires overriding all five lifecycle methods: `init`, `getServletConfig`, `service`, `getServletInfo`, and `destroy`. The `service` method handles client requests and responses, showcasing how to print output to the console and the browser, including handling character encoding for HTML responses. ```Java package com.mylifes1110.java; import javax.servlet.*; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; /** * Servlet * 实现Servlet接口中的所有方法 */ public class MyServlet implements Servlet { /** * 初始化方法 * * @param servletConfig 包含 servlet 的配置和初始化参数的 ServletConfig 对象 * @throws ServletException 如果发生妨碍 servlet 正常操作的异常 */ @Override public void init(ServletConfig servletConfig) throws ServletException { //Servlet初始化工作 } /** * 获取Servlet配置信息 * * @return 返回 ServletConfig 对象,该对象包含此 servlet 的初始化和启动参数。返回的 ServletConfig 对象是传递给 init 方法的对象。 */ @Override public ServletConfig getServletConfig() { return null; } /** * 提供服务 *

* 由 servlet 容器调用,以允许 servlet 响应某个请求。 * 此方法仅在 servlet 的 init() 方法成功完成之后调用。 * 应该为抛出或发送错误的 servlet 设置响应的状态代码。 * * @param servletRequest 包含客户端请求的 ServletRequest 对象 * @param servletResponse 包含 servlet 的响应的 ServletResponse 对象 * @throws ServletException 如果发生妨碍 servlet 正常操作的异常 * @throws IOException 果发生输入或输出异常 */ @Override public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { //请求相关内容 ServletRequest ; 相应相关内容 ServletResponse /** * 在控制台内打印输出 */ System.out.println("这是我的第一个Servlet!"); /** * 利用输出流输出系统时间,在浏览器中显示 */ PrintWriter printWriter = servletResponse.getWriter(); Date date = new Date(); printWriter.println(date); printWriter.close(); /** * 利用流输出信息在浏览器内显示 * 解决浏览器显示乱码问题 */ servletResponse.setContentType("text/html;charset=utf-8"); servletResponse.getWriter().println("这是我的第一个Servlet"); } /** * 返回有关 servlet 的信息,比如作者、版本和版权。 *

* 此方法返回的字符串应该是纯文本,不应该是任何种类的标记(比如 HTML、XML,等等)。 * * @return 包含 servlet 信息的 String */ @Override public String getServletInfo() { return null; } /** * 销毁(清除所有资源) *

* 由 servlet 容器调用,指示将从服务中取出该 servlet。 * 此方法仅在 servlet 的 service 方法已退出或者在过了超时期之后调用一次。 * 在调用此方法之后,servlet 容器不会再对此 servlet 调用 service 方法。 * 此方法为 servlet 提供了一个清除持有的所有资源(比如内存、文件句柄和线程)的机会,并确保任何持久状态都与内存中该 servlet 的当前状态保持同步。 */ @Override public void destroy() { } } ``` -------------------------------- ### Perform an Asynchronous GET Request with Native JavaScript Ajax Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/Frontend-Development/Ajax.md This JavaScript code snippet, embedded within a JSP page, demonstrates how to perform an asynchronous GET request using native XMLHttpRequest. It includes a cross-browser `createXMLHttpRequest` function, sets up an `onreadystatechange` callback to handle the server response, opens a GET connection with URL parameters, and sends the request. The response is parsed as JSON and logged to the console. ```HTML/JSP <%@ page contentType="text/html;charset=UTF-8" language="java" %> Ajax.Get ``` -------------------------------- ### Create Servlet to Display All Users in Java Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/Java-Web/Servlet基础.md This `HttpServlet` handles requests to the `/getAll` endpoint, retrieving all user information and rendering it as an HTML table. It calls the `UserService` to fetch user data and then uses `PrintWriter` to dynamically generate an HTML page displaying user IDs, usernames, passwords, and phone numbers. ```Java package com.mylifes1110.java.servlet; import com.mylifes1110.java.entity.User; import com.mylifes1110.java.service.UserService; import com.mylifes1110.java.service.impl.UserServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.List; /** * @author Ziph */ @WebServlet(name = "GetAllUserServlet", value = "/getAll") public class GetAllUserServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.调用Service response.setContentType("text/html;charset=utf-8"); UserService userService = new UserServiceImpl(); List userList = userService.inquireAll(); PrintWriter printWriter = response.getWriter(); //页面 printWriter.println(""); printWriter.println(""); printWriter.println(""); printWriter.println("查询所有"); printWriter.println(""); printWriter.println(""); printWriter.println(""); printWriter.println(""); printWriter.println(""); printWriter.println(""); printWriter.println(""); printWriter.println(""); for (User user : userList) { printWriter.println(""); printWriter.println(""); printWriter.println(""); printWriter.println(""); printWriter.println(""); printWriter.println(""); } printWriter.println("
编号用户名密码手机号
"); printWriter.println(user.getId()); printWriter.println(""); printWriter.println(user.getUsername()); printWriter.println(""); printWriter.println(user.getPassword()); printWriter.println(""); printWriter.println(user.getPhone()); printWriter.println("
"); printWriter.println(""); printWriter.println(""); printWriter.println(""); } } ``` -------------------------------- ### Example QR Code Payment Result Callback JSON Payload Source: https://github.com/ziphtracks/javalearningmanual/blob/master/project/小米商城/shopping/README.md This JSON payload is sent to the callback URL after a successful QR code payment. It contains detailed transaction information such as the application ID, merchant ID, transaction ID, the unique order number ('out_trade_no'), the total payment amount ('total_fee'), and the payment result code ('result_code'). The 'type' field indicates the communication method, where 0 signifies page redirection and 1 signifies point-to-point server communication (which may not be usable with localhost addresses). ```json { "result": { "appid":"wx632c8f211f8122c6", "bank_type":"CFT", "cash_fee":"1", "fee_type":"CNY", "is_subscribe":"Y", "mch_id":"1497984412", "nonce_str":"1631171182", "openid":"oUuptwrJudIfdihz1Z_T1AciMahs", "out_trade_no":"1221ea762d54496e83a33c9dab72f320", "result_code":"SUCCESS", "return_code":"SUCCESS", "sign":"5C7314AA4EB21772B42DBBCD65E56ACF", "time_end":"20180207163125", "total_fee":"1", "trade_type":"NATIVE", "transaction_id":"4200000065201802078895888133"}, "type":0 } ``` -------------------------------- ### Configure Servlet in web.xml Source: https://github.com/ziphtracks/javalearningmanual/blob/master/docs/Java-Web/Servlet基础.md This XML configuration snippet demonstrates how to register a Servlet and map it to a URL pattern within the `web.xml` deployment descriptor. It defines the Servlet's fully qualified class name using `` and its associated URL path for client access using ``. ```XML myservlet com.mylifes1110.java.MyServlet myservlet /test ```