一、前台表单
<form action="orgAdd.action" method="post">
组织名称:<input type="text" name="name" value=""/>
组织描述:<input type="text" name="description" value=""/>
<input type="submit" value="提交" />
</form>
二、后台Action类
public class OrgAddAction extends ActionSupport {
private String name;
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String execute() throws Exception {
System.out.println("组织名称:" + name);
}
}
三、结果输出
组织名称:???
四、问题解决办法
<struts>
<constant name="struts.i18n.encoding" value="GBK"/>
<package name="struts2" extends="struts-default">
<action name="orgAdd" class="orgAddAction">
<result name="success">/org/index.jsp</result>
</action>
</package>
</struts>
通过i18n(Internationalization 编码国际化)和 constant标签设置Action的传值编码为”GBK”,当然此编码要跟页面中的编码一致才不会造成中文乱码。
同时需要在web.xml中加上过滤器,如下:
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>GBK</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
编码过滤器必须加载在struts之前才能生效。