您的位置:首页 > 编程语言 > Java开发

Struts2 学习笔记 —— 10 —— Action接收参数时的中文乱码问题

2014-01-20 16:01 726 查看
在Struts接收参数时,如果输入中文,那么可能就会出现乱码问题

首先写一个index.jsp

<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<% String context = request.getContextPath(); %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<body>

使用DomainModel接收参数,测试中文问题<br><br>
<form action="<%= context%>/user/user!add">
姓名:<input type="text" name="user.name"></input><br><br>
密码:<input type="password" name="user.password"></input><br><br>
<input type="submit" value="submit">
</form>

</body>
</html>


我们发现使用Action传参数的时候使用POST方式也是可以的(之前用的都是GET方式传的参数)

结果发现输入中文后Action接收到的中文都是乱码



接收结果:



处理的方式应当是在struts.xml中加入

<constant name="struts.i18n.encoding" value="GBK" />


这句话会指定action的编码方式,将覆盖默认的struts的设置

PS:默认的struts的设置在这里



但是!!貌似加了这句话以后不管用,不知道是struts的bug还是出于什么考虑

解决办法:

1、可以再struts的filter之前配一个filter,更改request的值

2、不再使用struts2.1的配置,使用2.0的配置,见web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Struts2_0600_ActionWildcard</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>

<filter>
<filter-name>struts2</filter-name>
<!-- <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> -->
<filter-class>org.apache.struts2.dispatcher.FilterDispacher</filter-class>
</filter>

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

</web-app>


不知道有没有什么后遗症(我使用的2.3.16版本实验失败)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: