Table of Contents
1. Why packaging
2. How to package
1. Pack it into a jar package
1.1. Manual packaging using jar
1. 2. Use IDEA for packaging
2、打成war包
Home Java javaTutorial How to package a Java or Java Web project into a JAR package or WAR package

How to package a Java or Java Web project into a JAR package or WAR package

May 07, 2023 am 10:25 AM
java jar war

    1. Why packaging

    There are different opinions on this issue on the Internet. Based on personal understanding and online opinions, it is packaged as a jar package for the convenience of others. If you are running a java program, you do not need to look for the class containing the main method to execute; if you are using a third-party jar package, import the jar package directly into your own project instead of copying a bunch of class files. Building a war package is the web application deployment method chosen in real production environments. It is said online that this method will not cause file loss like directly copying folders, and the server will optimize the application, such as deleting empty folders, etc. The above is for information only.

    2. How to package

    The local environment is windows 10, jdk 1.8

    The same tool jdk/ is used to create jar or war packages bin/jar.exe

    1. Pack it into a jar package

    |-----------------You can skip it, just for the convenience of understanding the packaging Things to note------------------|

    Project Introduction

    Database table structure and table creation statements

    How to package a Java or Java Web project into a JAR package or WAR package

    CREATE TABLE `customer`  (
      `cust_id` int(11) NOT NULL AUTO_INCREMENT,
      `cust_name` char(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
      `cust_address` char(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
      `cust_city` char(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
      `cust_state` char(5) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
      `cust_zip` char(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
      `cust_country` char(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
      `cust_contact` char(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
      `cust_email` char(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
      PRIMARY KEY (`cust_id`) USING BTREE
    ) ENGINE = InnoDB AUTO_INCREMENT = 10006 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
    
    INSERT INTO `customer` VALUES (10001, 'Coyote Inc.', '200 Maple Lane', 'Detroit', 'MI', '44444', 'china', 'Y Lee', 'ylee@coyote.com');
    INSERT INTO `customer` VALUES (10002, 'Mouse House', '333 Fromage Lane', 'Columbus', 'OH', '43333', '', 'Jerry Mouse', NULL);
    INSERT INTO `customer` VALUES (10003, 'Wascals', '1 Sunny Place', 'Muncie', 'IN', '42222', 'USA', 'Jim Jones', 'rabbit@wascally.com');
    INSERT INTO `customer` VALUES (10004, 'Yosemite Place', '829 Riverside Drive', 'Phoenix', 'AZ', '88888', 'UK', 'Y Sam', 'sam@yosemite.com');
    INSERT INTO `customer` VALUES (10005, 'gzn or 1=1', '4545 53rd Street', 'Chicago', 'IL', '54545', '', 'E Fudd', NULL);
    Copy after login

    Project structure

    How to package a Java or Java Web project into a JAR package or WAR package

    app.java

    package com.gzn.demo;
    
    import java.sql.*;
    import java.util.Scanner;
    
    /**
     * @author: gzn
     * @date: 2019/4/13 10:53
     */
    public class App {
        public static void main(String[] args) {
    
            int count = Integer.valueOf(args[0]);
            System.out.println("请输入要查询用户的条数?(0到5之间):");
            Scanner sc = new Scanner(System.in);
            int count = sc.nextInt();
    
            String driver = "com.mysql.jdbc.Driver";
            String url = "jdbc:mysql://localhost:3306/corejava";
            String username = "root";
            String password = "root";
            String sql = "select cust_id, cust_name, cust_address, cust_city from customer limit 0, ? ";
    
            try {
                Class.forName(driver);
                Connection conn = DriverManager.getConnection(url, username, password);
                PreparedStatement pstat = conn.prepareStatement(sql);
                pstat.setInt(1, count);
                ResultSet rs = pstat.executeQuery();
                while(rs.next()) {
                    System.out.println("cust_id:" + rs.getObject("cust_id").toString());
                    System.out.println("cust_name: " + rs.getObject("cust_name").toString());
                    System.out.println("cust_address: " + rs.getObject("cust_address").toString());
                    System.out.println("cust_city:" + rs.getObject("cust_city").toString());
                    System.out.println("----------------------" +"\n");
                }
    
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    
    }
    Copy after login

    |----------- -------------------------------------------------- ----------------|

    1.1. Manual packaging using jar

    (1) Use cmd to find the path of the project compilation output

    How to package a Java or Java Web project into a JAR package or WAR package

    How to package a Java or Java Web project into a JAR package or WAR package

    (2) Run the command jar -cvf helloworld.jar .

    -c (create , create a file when creating a) table
    -v (verbose, lengthy, detailed) Print compression details on the console
    -f (filename) Specify the compressed file name
    helloworld.jar The file name can be customized Definition
    . Indicates all files in the helloworld directory. Be sure to write "." here, otherwise errors may occur. (Supplementary, * asterisks are also acceptable)

    How to package a Java or Java Web project into a JAR package or WAR package

    So far, the packaging is successful, but it cannot be run. If you want it to work, you need to modify the MANIFEST.MF file in helloword.jar.

    (3) Use the decompression tool to open helloword.jar and edit META-INF/MANIFEST.MF to add attributes

    MANIFEST.MF initial state

    Manifest-Version: 1.0
    Created-By: 1.8.0_161 (Oracle Corporation)
    Copy after login

    Add attributes: ( Note that the colon is an English colon and there is a space after the colon )

    Main-Class: The class containing the main method
    Class-Path: The path of the dependent jar package. If you rely on multiple jar packages, use spaces to separate them.
    Path: relative path, the path of the jar package relative to the helloworld.jar file
    Absolute path, the jar package is in the operating system Path
    Commonly used relative paths, put the dependent jar package and your own jar package in the same directory, so that Class-Path can directly write the name of the dependent jar package.

    Status after adding attributes:

    Manifest-Version: 1.0
    Created-By: 1.8.0_161 (Oracle Corporation)
    Class-Path: mysql-connector-java-5.1.18.jar
    Main-Class: com.gzn.demo.App
    Copy after login

    (4) Run the test
    Copy the dependencies to the directory of the same level as helloworld.jar, and use java -jar helloworld.jar to run the program.

    How to package a Java or Java Web project into a JAR package or WAR package

    How to package a Java or Java Web project into a JAR package or WAR package

    If the jar package is only for use by other developers and does not need to be run, proceed to step (2) .

    1. 2. Use IDEA for packaging

    How to package a Java or Java Web project into a JAR package or WAR package

    How to package a Java or Java Web project into a JAR package or WAR package

    ##Main Class: Contains the main method Class;
    extract to the target JAR: Extract the target jar. This option requires you to configure the absolute path for the dependent jar.
    copy to the output directory and link via manifest: Copy the dependent jar to the output directory, that is, at the same level as the jar packaged in your project. In this way, IDEA can directly configure the relative path for the Class-Path attribute in MENIFEST.MF.

    How to package a Java or Java Web project into a JAR package or WAR package

    #Output Directory: Packaged output path.

    Run the test:

    首先进入jar包输入路径C:\Users\gzn\Desktop\helloworld\out\artifacts\HelloWorld_jar;
    运行 java -jar helloworld.jar;

    How to package a Java or Java Web project into a JAR package or WAR package

    2、打成war包

    comment是我的一个已将编译好的web项目,使用cmd进入comment目录下执行命令

    jar -cvf comment.war .
    Copy after login

    How to package a Java or Java Web project into a JAR package or WAR package
    注意在项目目录下执行命令, “.” 表示对项目目录下的所有文件进行打包,将打包好的项目复制到Tomcat/webapps目录下,启动Tomcat服务器,就可以进行测试了。

    The above is the detailed content of How to package a Java or Java Web project into a JAR package or WAR package. For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Repo: How To Revive Teammates
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Hello Kitty Island Adventure: How To Get Giant Seeds
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

    Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

    Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

    Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

    Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

    Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

    Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

    Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

    Armstrong Number in Java Armstrong Number in Java Aug 30, 2024 pm 04:26 PM

    Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

    Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

    Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

    Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

    In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

    Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

    Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

    See all articles