当前位置: 首页 > 工具软件 > Open Liberty > 使用案例 >

使用Open Liberty创建maven web项目

金嘉言
2023-12-01
首先需要明确一个观点,如果你使用IBM发布的软件,开源也好,闭源也罢,你将不可避免的要用到IBM的一整套生态。

Open Liberty是IBM发布的开源的Java微服务运行时,精简版的WAS服务器。精简程度和地位类似于WildFly(原Jboss服务器)的全功能版与Servlet版,全功能版不是太重了么,搞个精简的可以跑一些基本的微服务和Servlet。一定程度上说是对开发者友好。能否将Open Liberty这个精简版的WAS服务器放到生产环境还有待观察,官方似乎也没给个教程啥的。

一、安装JDK8和maven
这里的JDK8不是传统意义上的Oracle JDK(sun被Oracle收购前成为sun JDK)而是ibm的JDK
maven安装方式不变

二、创建maven项目运行样例war
1.创建如下maven项目结构
项目名为ServletSampleServer
tree命令展示的项目结构
D:.
└─ServletSampleServer
    │  .gitignore
    │  pom.xml
    │  README.md
    │
    └─src
        └─main
            ├─java
            ├─liberty
            │  └─config
            ├─resources
            └─webapp

2.编辑pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>net.wasdev.wlp.maven.parent</groupId>
        <artifactId>liberty-maven-app-parent</artifactId>
        <version>2.0</version>
    </parent>
		<groupId>io.openliberty.guides</groupId>
		<artifactId>ServletSample</artifactId>
		<packaging>war</packaging>
		<version>1.0-SNAPSHOT</version>
    <!-- Add the rest of the POM below here. -->
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
		<app.name>${project.artifactId}</app.name>
		<testServerHttpPort>9080</testServerHttpPort>
		<testServerHttpsPort>9443</testServerHttpsPort>
		<warContext>${app.name}</warContext>
		<package.file>${project.build.directory}/${app.name}.zip</package.file>
		<packaging.type>usr</packaging.type>
	</properties>
	
	<dependencies>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>
	
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>3.1.0</version>
				<configuration>
					<packagingExcludes>pom.xml</packagingExcludes>
				</configuration>
			</plugin>
			<plugin>
				<groupId>net.wasdev.wlp.maven.plugins</groupId>
				<artifactId>liberty-maven-plugin</artifactId>
				<version>2.0</version>
				<configuration>
					<assemblyArtifact>
						<groupId>io.openliberty</groupId>
						<artifactId>openliberty-runtime</artifactId>
						<version>17.0.0.3</version>
						<type>zip</type>
					</assemblyArtifact>
					<serverName>${project.artifactId}Server</serverName>
					<stripVersion>true</stripVersion>
					<configFile>src/main/liberty/config/server.xml</configFile>
					<packageFile>${package.file}</packageFile>
					<include>${packaging.type}</include>
					<bootstrapProperties>
						<default.http.port>${testServerHttpPort}</default.http.port>
						<default.https.port>${testServerHttpsPort}</default.https.port>
						<app.context.root>${warContext}</app.context.root>
					</bootstrapProperties>
				</configuration>
				<executions>
					<execution>
						<id>package-server</id>
						<phase>package</phase>
						<goals>
							<goal>package-server</goal>
						</goals>
						<configuration>
							<outputDirectory>target/wlp-package</outputDirectory>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

</project>

3.使用maven命令运行
用cd命令跳转到pom.xml所在目录
先清理安装
mvn clean

再安装
mvn install

最后打包
mvn package

打包成功之后会在target目录生成文件
启动服务器
mvn liberty:start-server

启动之后可以通过如下地址访问首页
这个测试页面没啥东西,主要的东西都链接到官网
停止服务器
mvn liberty:stop-server
三、创建maven项目运行servlet
1.创建如下maven项目结构
D:.
└─ServletSample
    │  .gitignore
    │  pom.xml
    │  README.md
    │
    └─src
        ├─main
        │  ├─java
        │  │  └─io
        │  │      └─openliberty
        │  │          └─guides
        │  │              └─hello
        │  │                      HelloServlet.java
        │  │
        │  ├─liberty
        │  │  └─config
        │  │          server.xml
        │  │
        │  ├─resources
        │  └─webapp
        │      │  index.html
        │      │
        │      └─WEB-INF
        │              web.xml
        │
        └─test
            └─java
                └─io
                    └─openliberty
                        └─guides
                            └─hello
                                └─it
                                        EndpointIT.java

2.编辑pom.xml文件
<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>net.wasdev.wlp.maven.parent</groupId>
        <artifactId>liberty-maven-app-parent</artifactId>
        <version>2.0</version>
    </parent>
    <!-- Add the rest of the POM below here. -->
    <groupId>io.openliberty.guides</groupId>
    <artifactId>ServletSample</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <app.name>${project.artifactId}</app.name>
        <testServerHttpPort>9080</testServerHttpPort>
        <testServerHttpsPort>9443</testServerHttpsPort>
        <warContext>${app.name}</warContext>
        <package.file>${project.build.directory}/${app.name}.zip</package.file>
        <packaging.type>usr</packaging.type>
    </properties>
    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.1.0</version>
                <configuration>
                    <packagingExcludes>pom.xml</packagingExcludes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>net.wasdev.wlp.maven.plugins</groupId>
                <artifactId>liberty-maven-plugin</artifactId>
                <version>2.0</version>
                <configuration>
                    <assemblyArtifact>
                        <groupId>io.openliberty</groupId>
                        <artifactId>openliberty-runtime</artifactId>
                        <version>17.0.0.3</version>
                        <type>zip</type>
                    </assemblyArtifact>
                    <serverName>${project.artifactId}Server</serverName>
                    <stripVersion>true</stripVersion>
                    <configFile>src/main/liberty/config/server.xml</configFile>
                    <packageFile>${package.file}</packageFile>
                    <include>${packaging.type}</include>
                    <bootstrapProperties>
                        <default.http.port>${testServerHttpPort}</default.http.port>
                        <default.https.port>${testServerHttpsPort}</default.https.port>
                        <app.context.root>${warContext}</app.context.root>
                    </bootstrapProperties>
                </configuration>
                <executions>
                    <execution>
                        <id>package-server</id>
                        <phase>package</phase>
                        <goals>
                            <goal>package-server</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>target/wlp-package</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.19.1</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                        <configuration>
                            <includes>
                                <include>**/it/**</include>
                            </includes>
                            <systemPropertyVariables>
                                <liberty.test.port>${testServerHttpPort}</liberty.test.port>
                                <war.name>${warContext}</war.name>
                            </systemPropertyVariables>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>
3.编辑main下面的文件(这一部分的文件向导文档没有,要到github上找)
HelloServlet.java
package io.openliberty.guides.hello;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns="/servlet")
public class HelloServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().append("Hello! How are you today?\n");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

server.xml
<server description="Sample Servlet server">
    <featureManager>
        <feature>servlet-3.1</feature>
    </featureManager>

    <httpEndpoint httpPort="${default.http.port}" httpsPort="${default.https.port}" id="defaultHttpEndpoint"  host="*" />

    <webApplication id="ServletSample" location="ServletSample.war" contextRoot="${app.context.root}" />
</server>

index.html
<html>
<body>
<h2>Welcome to Hello Servlet</h2>  
<p>
<a href="servlet">Click here</a> to get a greeting from the Hello Servlet.
</p>    
</body>
</html>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">
    <display-name>Hello Servlet</display-name>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>

4.test下面的文件
EndpointIT.java
package io.openliberty.guides.hello.it;

import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;

public class EndpointIT {
    private static String URL;


    @BeforeClass
    public static void init() {

        String port = System.getProperty("liberty.test.port");
        String war = System.getProperty("war.name");
        URL = "http://localhost:" + port + "/" + war + "/" + "servlet";

    }

    @Test
    public void testServlet() throws Exception {
        HttpClient client = new HttpClient();

        GetMethod method = new GetMethod(URL);
        try {
            int statusCode = client.executeMethod(method);

            assertEquals("HTTP GET failed", HttpStatus.SC_OK, statusCode);

            String response = method.getResponseBodyAsString(1000);

            assertTrue("Unexpected response body", response.contains("Hello! How are you today?"));
        } finally {
            method.releaseConnection();
        }
    }
}

4.打包运行
安装
mvn install

打包
mvn package

打包时会跑一遍测试用例
可以看到Failures: 0说明打包成功
启动
mvn liberty:start-server

访问main里面的HelloServlet.java
停止
mvn liberty:stop-server


附:
参考资料:
1.OpenLiberty的github项目地址, https://github.com/OpenLiberty/open-liberty
3.建立一个maven web项目, https://www.openliberty.io/guides/maven-intro.html
4.建立一个maven web项目github版, https://github.com/OpenLiberty/guide-maven-intro

相关下载

向导文档的其它标题翻译
1.使用@CircuitBreaker 进行容错(微服务相关)
2.创建MicroProfile应用程序 (微服务相关)
3.创建HATEOAS 开发 REST 服务
4.访问RESTful web service
5.在Open Liberty启用CORS跨域访问
6.创建maven web项目
7.创建多模块应用程序(主要是EE的EAR打包项目)
8.创建RESTful web service

update2017-11-13:看了下CSDN最近的关于Open Liberty直播课程,有个表格提到这个 Open Liberty目前还不能用于生产环境,需要升级到WAS Liberty DD版,也就是说,开发完了想用起来还得用到IBM的生态闭环。







 类似资料: