通用
死记:
网址编解码:
// URI遇空格报错,故可清除左侧空格,将其他空格编码为 %2B 传至后端;若不转为URI则无需替换。
var r = URLEncoder.encode(" https://x/path?qs=a b ".replaceFirst("^\\s+", "").replaceAll("\\s", "+"));
URI.create(URLDecoder.decode(r)); // 后端会自动 decode 至 "https://x/path?qs=a++b+"
入参空格转码(不处理则报错) - URI.create("https://.../x?q=" + URLEncoder.encode("空 格", Charset.defaultCharset()));
注意 - HttpServletRequest.getInputStream()首次读取正常,再次读取会报 IllegalStateException ,可通过中间变量暂存。
解决中文乱码(Java18起默认已是UTF-8/Open Liberty InstantOn需设置) - response.setContentType("text/plain; charset=utf-8");
上传时,判断 request.getContentType() 后才能调 request.getPart("file");
字符串文件解析 new String(request.getPart("text").getInputStream().readAllBytes())
JPMS:
*.war\WEB-INF\classes\module-info.class 会被忽略,*.jar/module-info.class 才有效。
测试域名:
证书过期 - https://expired.badssl.com/
Java 内置 HttpClient 不读取系统证书目录,可代码指定.sslContext([Jetty SslContextFactory.Server 对象].getSslContext())
网络库:
IP国别判定(首选ip2region库) - implementation("com.github.jgonian:commons-ip-math:1.32") // Ipv6Range.parse(stringList[0]).contains(Ipv6.parse(ip));
Servlet:
[可选配置文件]web.xml - web-app_6_1.xsd 版本列表(不存在或写高了均取最高支持版本) web.xml 实例
Servlet支持版本 - quarkus-undertow为4.0,Open Liberty为6.1、Jetty是6.0。
识别不同请求 - System.identityHashCode(_HttpServletRequest)、不可逆哈希或更严谨的 request.getSession().getId()。
动态添加Servlet: _ServletContext.addServlet(...)
路径:request.getPathInfo() - 匹配 * 所在路径,即 "/hub/top/*" 不包含 /hub/top/ 星号前路径,/hub/top/x 取 /x。
Servlet CORS 跨域 Header
CDN:
implementation("org.apache.httpcomponents.client5:httpclient5-cache:5.6.4") // Servlet 承接请求并回源。
异步用法 - https://github.com/apache/httpcomponents-client/blob/master/httpclient5-cache/src/test/java/org/apache/hc/client5/http/cache/example/AsyncClientCacheRequestCollapsing.java
OpenLiberty:
OpenLiberty 官方称Ubuntu Beta镜像无计划提高当前的JDK17版本 - 仅用于 org.bytedeco:ffmpeg 安装 libxcb 相关库。
OpenLiberty 基于 CRIU 的快速启动容器镜像 - https://openliberty.io/docs/latest/instanton.html
支持 CPU x86-64-v2 构建的最后一个版本是 26.0.0.6,后续版本就得上 x86-64-v3 了。
v26.0.0.10+ 已明确支持 Java 27 了。
搬瓦工服务器报“Fatal glibc error: CPU does not support x86-64-v3” - icr.io/appcafe/open-liberty 改为最后一个支持 x86-64-v2 的容器 icr.io/appcafe/open-liberty:26.0.0.6-full-java25-openj9-ubi-minimal,latest 即 full 版。
Github Actions、Google Cloud Shell 均能正常构建 26.0.0.6(x86-64-v2)版本的 CRIU 镜像,x86-64-v3 也亲测 OK;检查点还原失败也能降级至常规启动:
CWWKE0961I: Restoring the checkpoint server process failed. ... Launching the server without using the checkpoint image.
Warn (criu/arch/x86/shstk.c:23): Restoring task with shadow stack on non-CET machine ...
server.xml 环境变量 OUR_PASSWORD 用法:dataSource 节点 properties password="${env.OUR_PASSWORD}";但 keyStore 节点 password 则要么明文,要么 securityUtility 编下码。
gradle 运行后 build\wlp\bin\securityUtility encode --encoding=aes-256 --key=加解密字符(只用于AES/亲测未成功!) OUR_KEYSTORE_PASSWORD 输出 {aes}AbCdAbcd
解码:<feature>passwordUtilities-1.1</feature> //System.setProperty("wlp.password.encryption.key", "加解密字符");
PasswordUtil.decode("{aes}AbCdAbcd"); // implementation("io.openliberty.features:passwordUtilities-1.1:25.0.0.9"){ exclude(group = "io.openliberty.features") }
Open Liberty - App.class.getResource("/x.wasm"); // wsjar:file:/opt/ol/wlp/usr/servers/defaultServer/apps/x.war!/WEB-INF/classes/x.wasm
path支持file和folder路径 - <library id="someLib"><path name="libs/lib-folder/ 或 lib.jar"/></library>
默认端口为 9080/9443。
HTTPS 协议
添加配置 https://github.com/OpenLiberty/ci.docker/blob/main/releases/latest/full/helpers/build/configuration_snippets/http-ssl-endpoint.xml 和 /opt/ol/helpers/build/configuration_snippets/tls.xml 至 /config/configDropins/overrides/
指定端口 docker run ... -e HTTPS_PORT=443
配置证书
<variable name="wlp.password.encryption.key" value="${env.OUR_KEYSTORE_PASSWORD}" />
<keyStore id="defaultKeyStore" location="/var/opt/our/keystore.p12" password="{aes}..." />
InstantOn 构建时直接用自动生成的 HTTPS 临时证书,运行时会遵照默认热更新配置 <config updateTrigger="polled" />,来秒内切换同路径真实证书。
HTTPS 协议详情:
说明 - 禁用 HTTPS 协议用 httpsPort="-1" 默认端口为 9443。
<feature>transportSecurity-1.0</feature>
<httpEndpoint id="defaultHttpEndpoint" ... httpsPort="${https.port}"><sslOptions sslRef="无此节点则取defaultSSLConfig" /></httpEndpoint>
密码至少6位,location="${server.output.dir}/resources/security/key.p12",即 defaultSSLConfig 默认的 keyStoreRef="defaultKeyStore"。
<!-- location与默认生成证书(key.p12)同名会被其覆盖,先测绝对路径;password 亲测明文或aes均可用。 -->
<keyStore id="defaultKeyStore" location="/opt/ol/wlp/usr/servers/defaultServer/resources/security/keystore.p12" password="明文或{aes}AbCdAbcd" />
非明文则还应提供:<variable name="wlp.password.encryption.key" value="${env.OUR_KEYSTORE_PASSWORD}" />
或独立文件提供:<include location="var.xml" /> 包含 <server><variable ... /></server>
jar包类优先于war同名类:<webApplication location="appThatNeedsFix.war"><classloader overrideLibraryRef="someImplFix"/></webApplication>
CORS 跨域:
<cors domain="/main/apis/more/default/" allowedMethods="OPTIONS,GET,POST,PUT,DELETE"
exposeHeaders="*" allowedHeaders="*" allowCredentials="true"
allowedOrigins="https://a.com,https://b.com" />
<cors domain="/more/path" ... />
restfulWS 模块儿支持 jakarta.ws.rs.core.StreamingOutput
常用:
request.getParameter("url") 会自动解码 URLEncoder.encode(request.getRequestURL().toString() + "?" + request.getQueryString(), Charset.defaultCharset());
// 首个空参数 ?& 便于后续只处理&符号。
var p1="k=v"; "https://example.com/path/?&" + p1 + "&" + p2;
JAX-RS中必须调用flush()来刷新缓存区,否则响应HTTP 204: response.getWriter().print(jsScript); response.getWriter().flush();
Cookie - response.addCookie(cv); // 无法被本请求的 request.getCookies() 感知到。
Session - request.getSession(false) 过期设置 web.xml :
<web-app ...>
<session-config><session-timeout>-1</session-timeout><cookie-config><max-age>[默认]浏览器关闭JSESSIONID即失效</max-age></cookie-config></session-config>
</web-app>
或 session.setMaxInactiveInterval(30 * 60); // 仅生效在当前请求上下文,单位秒。
JAX-RS解决JSON Binding (JSON-B)报错 - Could not find MessageBodyWriter for response object of type: pkg.JavaRecord$OrPOJO of media type: application/json
引入库 yasson ;若为 OpenLiberty 则添加 jsonb-3.0
JAX-RS SSE(Server-Sent Events):
每个 Servlet 请求均不为 null - @Context Sse sse; 但 @Context SseEventSink ses; 只有在 SSE 请求里才不为 null。
jakarta.ws.rs.sse.SseEventSink,也能用 Servlet 流式响应 asyncSupported=true 模拟。
1分20秒重连问题解决 - 开长连接、关闭缓存:(尽量不要在VPN网络下测试)location = /apis/add-video-watermark {
proxy_http_version 1.1; # 默认的1.0不支持Keep-Alive,而1.1则默认处于长连接。
proxy_buffering off; # 关闭响应缓存,关闭后会连带proxy_cache也处于off,类似no-cache。
proxy_set_header Connection '';
proxy_read_timeout 500;
proxy_pass http://ip:9080; # SSE不能用在try_files指令
}
必须的响应头:
Content-Type: text/event-stream
Cache-Control: no-cache
Connection: keep-alive