Servlet 与 tomcat 避坑指南
- 无法打开登录管理页面。
修改 conf/tomcat-users.xml,在文件中加入以下两行。
代码语言:javascript复制 <role rolename="manager-gui,admin-gui"/>
<user username="ivandu" password="drh123" roles="manager-gui,admin-gui"/>
- 远程主机无法登录管理页面。
修改应用下面的 META-INF/context.xml 把<Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="127.d .d .d |::1|0:0:0:0:0:0:0:1" />
中 allow 后面的内容,例如改为 10 网段可以访问:
<Context antiResourceLocking="false" privileged="true" >
<CookieProcessor className="org.apache.tomcat.util.http.Rfc6265CookieProcessor"
sameSiteCookies="strict" />
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow="10.d .d .d |::1|0:0:0:0:0:0:0:1" />
<Manager sessionAttributeValueClassNameFilter="java.lang.(?:Boolean|Integer|Long|Number|String)|org.apache.catalina.filters.CsrfPreventionFilter$LruCache(?:$1)?|java.util.(?:Linked)?HashMap" />
</Context>
新增某指定 IP 的主机能访问,例如新增 IP 为 10.1.1.2 的主机访问 manager 和 host-manager 两个应用,在 webapps/manager/META-INF/context.xml 和 webapps/host-manager/META-INF/context.xml 文件中做如下修改:
代码语言:javascript复制<Context antiResourceLocking="false" privileged="true" >
<CookieProcessor className="org.apache.tomcat.util.http.Rfc6265CookieProcessor"
sameSiteCookies="strict" />
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow="10.1.1.2|127.d .d .d |::1|0:0:0:0:0:0:0:1" />
<Manager sessionAttributeValueClassNameFilter="java.lang.(?:Boolean|Integer|Long|Number|String)|org.apache.catalina.filters.CsrfPreventionFilter$LruCache(?:$1)?|java.util.(?:Linked)?HashMap"/>
</Context>
- tomcat 10 编译、部署时提示"程序包javax.servlet不存在"。
tomcat 10 中 servlet 相关的包名已经由 javax 变更为 jakarta,该版本的tomcat支持 java ee9 的部分实现,servlet 升级到 5.0。目前 maven 仓库还没有 servlet 5.0 相关的仓库。 版本支持情况。
- Servlet 项目中的 web.xml 无需死记硬背,可以从 tomcat 的 conf 目录下拷贝。例如 tomcat9.0.46:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<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_4_0.xsd"
version="4.0">
</xml-app>
- request.getRemoteAddr()获取的IP一般默认为IPv6,要转换为IPv4需要配置Tomcat的vm选项:
-Djava.net.preferIPv4Stack=true
- 服务器输出 UTF-8 日志显示乱码的解决方法,在 VM 选项增加:
-Dfile.encoding=UTF-8