You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Struts2含特殊字符的命名变量URL无法匹配Action问题求助

Struts2含特殊字符(é、ñ)的URL无法匹配Action的解决方法

你的问题核心是正则表达式未覆盖ñ这类特殊字符,加上容器和Struts2自身的编码配置可能存在疏漏,导致带重音、ñ的URL片段无法被正确识别匹配。以下是具体解决步骤:

1. 修正struts.allowed.action.names的正则规则

你当前配置的[ a-zA-Zà-úÀ-Ú0-9\.\_\-]*正则中,à-ú的范围并不包含ñ/Ñ字符,必须手动添加进去。修改后的配置如下:

<constant name="struts.allowed.action.names" value="[a-zA-Zà-úÀ-ÚñÑ0-9\.\_\-\s]*"/>

2. 补充Struts2编码相关常量

确保Struts2全程使用UTF-8处理字符,避免编码转换导致的匹配失败,在struts.xml中添加:

<constant name="struts.i18n.encoding" value="UTF-8"/>
<constant name="struts.url.encoding" value="UTF-8"/>

完整的struts.xml配置示例:

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <constant name="struts.allowed.action.names" value="[a-zA-Zà-úÀ-ÚñÑ0-9\.\_\-\s]*"/>
    <constant name="struts.patternMatcher" value="regex" />
    <constant name="struts.matcher.appendNamedParameters" value="true"/>
    <constant name="struts.i18n.encoding" value="UTF-8"/>
    <constant name="struts.url.encoding" value="UTF-8"/>
</struts>

3. 配置Web容器的URI编码

以Tomcat为例,需要在server.xml的Connector节点中添加URIEncoding="UTF-8",确保容器能正确解码URL中的特殊字符:

<Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="8443"
           URIEncoding="UTF-8"/>

4. 检查Action参数接收

确保Action类中对应的参数(state、category、name)是String类型,并且有正确的getter和setter方法,比如:

public class DisplayAction extends ActionSupport {
    private String state;
    private String category;
    private String name;

    // Getters and Setters
    public String getState() { return state; }
    public void setState(String state) { this.state = state; }
    public String getCategory() { return category; }
    public void setCategory(String category) { this.category = category; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    @Action(value = "/display/{state}/{category}/{name}", results = {
        @Result(name = "home", type="tiles", location="home")
    })
    public String execute() {
        // 业务逻辑
        return "home";
    }
}

完成以上配置后,带é、ñ的URL(如domain/display/méxico/others/josé)就能正确匹配到对应的Action了。

内容的提问来源于stack exchange,提问作者Jose

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 04:52:36