表单提交中文乱码问题

时间:2022-01-21 13:04:38
这是一个网上书店的后台管理系统,采用SSH框架。通过struts接收命令,然后由spring托管,通过hibernate操作数据库,这里数据库用的是MySQL

现在的问题是,表单提交的中文数据变成了乱码,通过输出测试,提交表单后,在**FORM中就变成了乱码。但是如果从数据库中读取中文返回给JSP,JSP是能够正常显示的。那么这里乱码究竟是在哪个传递过程中出现问题的呢?

网页和配置文件等的编码设置都是UTF-8,不过读取数据库中文数据显示正常,应该不会是这个问题吧。而且我也尝试过改成gb2312,但仍然是乱码,望赐教。

客户添加 clients_add.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<%@ taglib uri="http://struts.apache.org/tags-nested" prefix="nested"%>
<html:html locale = "true"/> 
<%String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>��ӿͻ�客户添加</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>

<body>
<TABLE width="100%" class="position">
<TR>
<TD>当前位置:客户管理->客户添加</TD>
<TD align="right"><a href="clients.do?method=list">返回</a></TD>
<TD width="20"></TD>
</TR>
</TABLE>
<form name="form1" action="clients_add.do?method=insert" method="post">
<b><html:errors property="org.apache.struts.action.GLOBAL_MESSAGE" /></b>
<TABLE border="0" width="100%">
<TR>
<td>姓名</td>
<td><logic:present name="clientsFormBean">
<html:text property="cname" name="clientsFormBean"/>
</logic:present>
<logic:notPresent name="clientsFormBean">
<input type="text" name="cname">
</logic:notPresent>
<html:errors property="cname"/></td>
</TR>
<TR>
<td>性别</td>
<td><logic:present name="clientsFormBean">
<html:text property="sex" name="clientsFormBean"/>
</logic:present>
<logic:notPresent name="clientsFormBean">
<input type="text" name="sex"></logic:notPresent>
</td>
</TR>
<TR>
<td>电话</td>
<td><logic:present name="clientsFormBean">
<html:text property="phone" name="clientsFormBean"/>
</logic:present>
<logic:notPresent name="clientsFormBean">
<input type="text" name="phone">
</logic:notPresent>
<html:errors property="phone1"/>
<html:errors property="phone2"/>
</td>
</TR>
<TR>
<td>地址</td>
<td><logic:present name="clientsFormBean">
<html:text property="address" name="clientsFormBean"/>
</logic:present>
<logic:notPresent name="clientsFormBean">
<input type="text" name="address"></logic:notPresent>
</td>
</TR>
<TR>
<td>邮编</td>
<td><logic:present name="clientsFormBean">
<html:text property="post" name="clientsFormBean"/>
</logic:present>
<logic:notPresent name="clientsFormBean">
<input type="text" name="post"></logic:notPresent>
<html:errors property="post"/>
</td>
</TR>
<TR>
<TD>Email</TD>
<td><logic:present name="clientsFormBean">
<html:text property="email" name="clientsFormBean"/>
</logic:present>
<logic:notPresent name="clientsFormBean">
<input type="text" name="email"></logic:notPresent>
<html:errors property="email"/>
</td>
</TR>
<TR>
<TD colspan="2"><input type="submit" value="添加"></TD>
</TR>
</TABLE>
</form>
</body>
</html>

17 个解决方案

#1



ClientsForm.java
package com.bookstoreonline.struts.forms;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

import com.bookstoreonline.struts.util.RegExpression;

public class ClientsForm extends ActionForm {

/**
 * 
 */
private static final long serialVersionUID = 1L;

protected int cid=0;

protected String cname=null;

protected String sex=null;

protected String phone=null;

protected String address=null;

protected String post=null;

protected String email=null;

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public int getCid() {
return cid;
}

public void setCid(int cid) {
this.cid = cid;
}

public String getCname() {
return cname;
}

public void setCname(String cname) {
this.cname = cname;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

public String getPost() {
return post;
}

public void setPost(String post) {
this.post = post;
}

public String getSex() {
return sex;
}

public void setSex(String sex) {
this.sex = sex;
}

public ActionErrors validate(ActionMapping arg0, HttpServletRequest arg1) {
ActionErrors errors = new ActionErrors();
String queryString = arg1.getQueryString();
if (queryString.equalsIgnoreCase("method=insert")
|| queryString.equalsIgnoreCase("method=update")) {
//check name
if (cname == null || cname.equals("")) {
errors.add("cname", new ActionMessage("clients.error.cname"));
}

//check phone
if (phone == null || phone.equals("")) {
errors.add("phone1", new ActionMessage("clients.error.phone1"));
}
else {
Pattern p_phone = Pattern.compile(RegExpression.REG_phone);
Matcher m_mobile = p_phone.matcher(phone);
if (!m_mobile.find()) {
errors.add("phone2", new ActionMessage("clients.error.phone2"));
}
}

//check email
if (email != null && !email.equals("")) {
Pattern p_email = Pattern.compile(RegExpression.REG_email);
Matcher m_email = p_email.matcher(email);
if (!m_email.find()) {
errors.add("email", new ActionMessage("clients.error.email"));
}
}

//check postcode
if (post != null && !post.equals("")) {
Pattern p_postcode = Pattern.compile(RegExpression.REG_post);
Matcher m_postcode = p_postcode.matcher(post);
if (!m_postcode.find()) {
errors.add("post", new ActionMessage("clients.error.post"));
}
}
}
System.out.println("prince1:"+this.getCname());
arg1.setAttribute("clientsFormBean", this);
return errors;
}

}

#2



ClientsAction.java
package com.bookstoreonline.struts.actions;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.DispatchAction;

import com.bookstoreonline.hibernate.beans.Clients;
import com.bookstoreonline.hibernate.dao.ClientsDAO;
import com.bookstoreonline.struts.forms.ClientsForm;

public class ClientsAction extends DispatchAction {

protected ClientsDAO clientsDAO;

Logger log = Logger.getLogger(this.getClass());

public ClientsDAO getClientsDAO() {
return clientsDAO;
}

public void setClientsDAO(ClientsDAO clientsDAO) {
this.clientsDAO = clientsDAO;
}

public ActionForward list(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
List list=clientsDAO.findAll();
request.setAttribute("clientsList", list);
ActionForward forward = mapping.findForward("list");
return (forward);
}

public ActionForward add(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = mapping.findForward("add");
return (forward);
}

public ActionForward insert(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionMessages messages = new ActionMessages();
ClientsForm clientsForm = (ClientsForm) form;
// insert object
Clients clients = new Clients();
/*clients.setCname(clientsForm.getCname());
clients.setAddress(clientsForm.getAddress());
clients.setEmail(clientsForm.getEmail());
clients.setPhone(clientsForm.getPhone());
clients.setPost(clientsForm.getPost());
clients.setSex(clientsForm.getSex());*/
clients.setCname("李四");
clients.setAddress("南京市");
clients.setEmail("l4@163.com");
clients.setPhone("15812345678");
clients.setPost("123456");
clients.setSex("女");
clientsDAO.insert(clients);
// save messages
messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
"clients.message.add.success"));
saveErrors(request, messages);
List list=clientsDAO.findAll();
request.setAttribute("clientsList", list);
return mapping.findForward("list");
}

public ActionForward edit(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionMessages messages = new ActionMessages();
String cid = request.getParameter("cid");
// get object
Clients clients = clientsDAO.findById(cid);

// save form object
ClientsForm clientsForm = new ClientsForm();
clientsForm.setCid(clients.getCid());
clientsForm.setCname(clients.getCname());
clientsForm.setSex(clients.getSex());
clientsForm.setPhone(clients.getPhone());
clientsForm.setEmail(clients.getEmail());
clientsForm.setAddress(clients.getAddress());
clientsForm.setPost(clients.getPost());

// save in request
request.setCharacterEncoding("gb2312");
request.setAttribute("clientsFormBean", clientsForm);

return mapping.findForward("edit");
}

public ActionForward update(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionMessages messages = new ActionMessages();
ClientsForm clientsForm = (ClientsForm) form;
Clients clients = new Clients();

// update object
clients.setCid(new Integer(clientsForm.getCid()));
clients.setCname(clientsForm.getCname());
clients.setSex(clientsForm.getSex());
clients.setPhone(clients.getPhone());
clients.setEmail(clientsForm.getEmail());
clients.setAddress(clientsForm.getAddress());
clients.setPost(clientsForm.getPost());
clientsDAO.update(clients);

// save messages
messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
"clients.message.edit.success"));
saveErrors(request, messages);
List list=clientsDAO.findAll();
request.setAttribute("clientsList", list);
ActionForward forward = mapping.findForward("list");
return (forward);
}

public ActionForward delete(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionMessages messages = new ActionMessages();

String cid = request.getParameter("cid");
if (cid == null) {
// if id not exist
messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
"address.message.edit.notexist"));
} else {
// delete object
clientsDAO.delete(cid);

// save messages
messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
"clients.message.delete.success"));
}
saveErrors(request, messages);
List list=clientsDAO.findAll();
request.setAttribute("clientsList", list);
return mapping.findForward("list");
}
}

#3



Clients.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="com.bookstoreonline.hibernate.beans.Clients" table="clients" catalog="bookstore">
        <id name="cid" type="java.lang.Integer">
            <column name="cid" />
            <generator class="native" />
        </id>
        <property name="cname" type="java.lang.String">
            <column name="cname" />
        </property>
        <property name="sex" type="java.lang.String">
            <column name="sex" />
        </property>
        <property name="phone" type="java.lang.String">
            <column name="phone" />
        </property>
        <property name="address" type="java.lang.String">
            <column name="address" />
        </property>
        <property name="post" type="java.lang.String">
            <column name="post" />
        </property>
        <property name="email" type="java.lang.String">
            <column name="email" />
        </property>
    </class>
</hibernate-mapping>


struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">

<struts-config>
  <!--
  <data-sources>
<data-source type="org.apache.commons.dbcp.BasicDataSource">
<set-property property="driverClassName"
value="com.mysql.jdbc.Driver" />
<set-property property="url"
value="jdbc:mysql://localhost:3306/bookstore" />
<set-property property="username" value="root" />
<set-property property="password" value="00000000" />
<set-property property="maxActive" value="10" />
<set-property property="maxWait" value="5000" />
<set-property property="defaultAutoCommit" value="false" />
<set-property property="defaultReadOnly" value="false" />
<set-property property="validationQuery"
value="SELECT COUNT(*) FROM manages" />
</data-source>
  </data-sources>
  -->
  <form-beans>
<form-bean name="loginForm"
type="com.bookstoreonline.struts.forms.LoginForm">
</form-bean>
<form-bean name="clientsForm"
type="com.bookstoreonline.struts.forms.ClientsForm">
</form-bean>
  </form-beans>
  <global-exceptions />
  <global-forwards />
  <action-mappings>
<action path="/index" forward="/login.jsp" />
<action path="/welcome" forward="/welcome.jsp" />

<action path="/login" name="loginForm" scope="request"
type="org.springframework.web.struts.DelegatingActionProxy" input="/login.jsp">
<forward name="success" path="/welcome.jsp" />
<forward name="failure" path="/login.jsp" />
</action>

<action path="/logout"
type="org.springframework.web.struts.DelegatingActionProxy">
<forward name="logout" path="/login.jsp" />
</action>

<action path="/clients" parameter="method" name="pageForm" scope="request"
type="org.springframework.web.struts.DelegatingActionProxy">
<forward name="list" path="/clients.jsp" />
</action>
<action path="/clients_add" parameter="method" name="clientsForm" scope="request"
type="org.springframework.web.struts.DelegatingActionProxy"
input="/clients_add.jsp">
<forward name="list" path="/clients.jsp" />
<forward name="add" path="/clients_add.jsp" />
</action>
<action path="/clients_edit" parameter="method" name="clientsForm" scope="request"
type="org.springframework.web.struts.DelegatingActionProxy"
input="/clients_edit.jsp">
<forward name="list" path="/clients.jsp" />
<forward name="edit" path="/clients_edit.jsp" />
</action>
</action-mappings>
  <message-resources parameter="com.bookstoreonline.struts.resources.ApplicationResources" />
</struts-config>


applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/bookstore</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>00000000</value>
</property>
</bean>

<!-- �������� -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource">
<ref local="dataSource" />
</property>
</bean>

<!-- ����Hibernate -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref local="dataSource" />
</property>
<property name="mappingResources">
<list>
<value>com/bookstoreonline/hibernate/beans/Manages.hbm.xml</value>
<value>
com/bookstoreonline/hibernate/beans/Clients.hbm.xml
</value></list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>

<!-- ����DAO -->
<bean id="managesDAO" class="com.bookstoreonline.hibernate.dao.ManagesDAO">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
<bean id="clientsDAO" class="com.bookstoreonline.hibernate.dao.ClientsDAO">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>

<!-- ����DAO���� -->
<bean id="ManagesDAOProxy"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
<property name="target">
<ref local="managesDAO" />
</property>
<property name="transactionAttributes">
<props>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
<bean id="ClientsDAOProxy"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
<property name="target">
<ref local="clientsDAO" />
</property>
<property name="transactionAttributes">
<props>
<prop key="insert">PROPAGATION_REQUIRED</prop>
<prop key="update">PROPAGATION_REQUIRED</prop>
<prop key="delete">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>

<!-- ����Struts���� -->
<bean name="/login" class="com.bookstoreonline.struts.actions.LoginAction">
<property name="managesDAO">
<ref local="managesDAO" />
</property>
</bean>
<bean name="/logout" class="com.bookstoreonline.struts.actions.LogoutAction">
<property name="managesDAO">
<ref local="managesDAO" />
</property>
</bean>
<bean name="/clients"
class="com.bookstoreonline.struts.actions.ClientsAction">
<property name="clientsDAO">
<ref local="clientsDAO" />
</property>
</bean>
<bean name="/clients_add"
class="com.bookstoreonline.struts.actions.ClientsAction">
<property name="clientsDAO">
<ref local="clientsDAO" />
</property>
</bean>
<bean name="/clients_edit"
class="com.bookstoreonline.struts.actions.ClientsAction">
<property name="clientsDAO">
<ref local="clientsDAO" />
</property>
</bean>
</beans>

#4


在web.xml中配置这个就行了啊!
<!-- 中文乱码处理 -->
  <filter>
  <filter-name>filter</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>

#5


进来学习学习!

#6


顶四楼,加一个SPRING的过滤器.还有不要忘记页面编码和服务器的编码要一致

#7


关注中。。。

#8


引用 4 楼 pengpeng409 的回复:
在web.xml中配置这个就行了啊! 
<!-- 中文乱码处理 --> 
  <filter> 
  <filter-name>filter </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> 
   <filter-name>filter</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>filter</filter-name>  
   <servlet-name>/*</servlet-name>  
  </filter-mapping> 

可是仍然是乱码,楼上说的页面编码和服务器的编码要一致,服务器编码是指哪个啊?

我在加了这么一段之后,其他地方的编码需要改动么,我现在还是保留UTF-8

另外可不可能是post方式提交或request、response的问题呢,我对**FORM获取表单内容的过程不太清楚,它是如何根据名称获取的呢

#9


补充一句,ClientsAction.java 中的insert方法,被注释掉的方法是正常的读取表单内容然后写入数据库中的代码,我为了测试是不是写入数据库的过程中出现了问题,所以将其注释而用指定的中文数据插入测试,结果插入的数据是乱码说明这个过程有问题

然后在ClientsForm.java 中,validate方法里加了一句 System.out.println("prince1:"+this.getCname());这是想测试ClientsForm接收表单数据的过程中是否有问题,结果输出的结果也是乱码,说明这个过程也有问题
那该怎么解决呢?

#10


表单提交都是通过servlet调post()或get()方法处理的,再把结果返回到客户端。
有做过滤器吗,写个过滤类,表单提交都先到servlet请求,如果在请求前加个过滤器,将字符都转为中文再进行处理。
public void doFilter(ServletRequest request, ServletResponse response, 
FilterChain chain) throws IOException, ServletException { 

HttpServletRequest request_1 = (HttpServletRequest) request; 
HttpServletResponse response_1 = (HttpServletResponse) response; 

// 转换编码,并且加上去缓存 
request_1.setCharacterEncoding("GBK"); 
response_1.setCharacterEncoding("GBK"); 
chain.doFilter(request, response); 


#11


前台后台服务器都要统一,你的过滤器里怎么是GBK?应该用UTF-8吧

#12


页面上的只是显示的编码吧,并不是请求的编码,后台和request的字符集保持一致就行,
前台页面和查询结果的字符集保持一致

#13


引用 10 楼 fafuhefan 的回复:
表单提交都是通过servlet调post()或get()方法处理的,再把结果返回到客户端。 
有做过滤器吗,写个过滤类,表单提交都先到servlet请求,如果在请求前加个过滤器,将字符都转为中文再进行处理。 

Java codepublic void doFilter(ServletRequest request, ServletResponse response, 
FilterChain chain) throws IOException, ServletException { 

HttpServletRequest request_1 = (HttpServletRequest) request; 
HttpSe…


我加了这么一个过滤器,按11楼说的都统一改成UTF-8
结果是表单提交数据到ACTION FORM是正确的,但是ACTIONFORM数据写入数据库的中文还是不正确,一个汉字变成了两个问号

#14


呵呵
这个乱码的问题我见到的比较多
你可以写个过滤器很简单的
源码青加QQ群76208671

#15



由于Java默认的编码方式是UNICODE,所以用中文易出问题,常用解决:
String s2 = new String(s1.getBytes(“ISO-8859-1”),”GBK”);

utf-8解决JSP中文乱码问题,在页面的开始处加:
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <%request.setCharacterEncoding("UTF-8");%>

如果仍不能解决问题,还需要这样处理一下:
String msg = request.getParameter("message");
String str=new String(msg.getBytes("ISO-8859-1"),"UTF-8");out.println(st); 

#16


找到问题的原因了,后来的写数据库的乱码问题是数据库设置没有设置编码

我在applicationcontext.xml中的数据库设置为

 </property>
        <property name="url">
        <value>jdbc:mysql://localhost:3306/bookstore</value>
 </property>

现在改成jdbc:mysql://localhost:3306/bbs?useUnicode=true&amp;characterEncoding=utf-8 就没有问题了

这样从页面到服务器到数据库都是统一的UTF-8编码了

#17


所以说对于中文问题,一个是用过滤器过滤传递过程的编码,再一个还是要注意数据库编码

#1



ClientsForm.java
package com.bookstoreonline.struts.forms;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

import com.bookstoreonline.struts.util.RegExpression;

public class ClientsForm extends ActionForm {

/**
 * 
 */
private static final long serialVersionUID = 1L;

protected int cid=0;

protected String cname=null;

protected String sex=null;

protected String phone=null;

protected String address=null;

protected String post=null;

protected String email=null;

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public int getCid() {
return cid;
}

public void setCid(int cid) {
this.cid = cid;
}

public String getCname() {
return cname;
}

public void setCname(String cname) {
this.cname = cname;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

public String getPost() {
return post;
}

public void setPost(String post) {
this.post = post;
}

public String getSex() {
return sex;
}

public void setSex(String sex) {
this.sex = sex;
}

public ActionErrors validate(ActionMapping arg0, HttpServletRequest arg1) {
ActionErrors errors = new ActionErrors();
String queryString = arg1.getQueryString();
if (queryString.equalsIgnoreCase("method=insert")
|| queryString.equalsIgnoreCase("method=update")) {
//check name
if (cname == null || cname.equals("")) {
errors.add("cname", new ActionMessage("clients.error.cname"));
}

//check phone
if (phone == null || phone.equals("")) {
errors.add("phone1", new ActionMessage("clients.error.phone1"));
}
else {
Pattern p_phone = Pattern.compile(RegExpression.REG_phone);
Matcher m_mobile = p_phone.matcher(phone);
if (!m_mobile.find()) {
errors.add("phone2", new ActionMessage("clients.error.phone2"));
}
}

//check email
if (email != null && !email.equals("")) {
Pattern p_email = Pattern.compile(RegExpression.REG_email);
Matcher m_email = p_email.matcher(email);
if (!m_email.find()) {
errors.add("email", new ActionMessage("clients.error.email"));
}
}

//check postcode
if (post != null && !post.equals("")) {
Pattern p_postcode = Pattern.compile(RegExpression.REG_post);
Matcher m_postcode = p_postcode.matcher(post);
if (!m_postcode.find()) {
errors.add("post", new ActionMessage("clients.error.post"));
}
}
}
System.out.println("prince1:"+this.getCname());
arg1.setAttribute("clientsFormBean", this);
return errors;
}

}

#2



ClientsAction.java
package com.bookstoreonline.struts.actions;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.DispatchAction;

import com.bookstoreonline.hibernate.beans.Clients;
import com.bookstoreonline.hibernate.dao.ClientsDAO;
import com.bookstoreonline.struts.forms.ClientsForm;

public class ClientsAction extends DispatchAction {

protected ClientsDAO clientsDAO;

Logger log = Logger.getLogger(this.getClass());

public ClientsDAO getClientsDAO() {
return clientsDAO;
}

public void setClientsDAO(ClientsDAO clientsDAO) {
this.clientsDAO = clientsDAO;
}

public ActionForward list(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
List list=clientsDAO.findAll();
request.setAttribute("clientsList", list);
ActionForward forward = mapping.findForward("list");
return (forward);
}

public ActionForward add(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = mapping.findForward("add");
return (forward);
}

public ActionForward insert(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionMessages messages = new ActionMessages();
ClientsForm clientsForm = (ClientsForm) form;
// insert object
Clients clients = new Clients();
/*clients.setCname(clientsForm.getCname());
clients.setAddress(clientsForm.getAddress());
clients.setEmail(clientsForm.getEmail());
clients.setPhone(clientsForm.getPhone());
clients.setPost(clientsForm.getPost());
clients.setSex(clientsForm.getSex());*/
clients.setCname("李四");
clients.setAddress("南京市");
clients.setEmail("l4@163.com");
clients.setPhone("15812345678");
clients.setPost("123456");
clients.setSex("女");
clientsDAO.insert(clients);
// save messages
messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
"clients.message.add.success"));
saveErrors(request, messages);
List list=clientsDAO.findAll();
request.setAttribute("clientsList", list);
return mapping.findForward("list");
}

public ActionForward edit(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionMessages messages = new ActionMessages();
String cid = request.getParameter("cid");
// get object
Clients clients = clientsDAO.findById(cid);

// save form object
ClientsForm clientsForm = new ClientsForm();
clientsForm.setCid(clients.getCid());
clientsForm.setCname(clients.getCname());
clientsForm.setSex(clients.getSex());
clientsForm.setPhone(clients.getPhone());
clientsForm.setEmail(clients.getEmail());
clientsForm.setAddress(clients.getAddress());
clientsForm.setPost(clients.getPost());

// save in request
request.setCharacterEncoding("gb2312");
request.setAttribute("clientsFormBean", clientsForm);

return mapping.findForward("edit");
}

public ActionForward update(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionMessages messages = new ActionMessages();
ClientsForm clientsForm = (ClientsForm) form;
Clients clients = new Clients();

// update object
clients.setCid(new Integer(clientsForm.getCid()));
clients.setCname(clientsForm.getCname());
clients.setSex(clientsForm.getSex());
clients.setPhone(clients.getPhone());
clients.setEmail(clientsForm.getEmail());
clients.setAddress(clientsForm.getAddress());
clients.setPost(clientsForm.getPost());
clientsDAO.update(clients);

// save messages
messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
"clients.message.edit.success"));
saveErrors(request, messages);
List list=clientsDAO.findAll();
request.setAttribute("clientsList", list);
ActionForward forward = mapping.findForward("list");
return (forward);
}

public ActionForward delete(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionMessages messages = new ActionMessages();

String cid = request.getParameter("cid");
if (cid == null) {
// if id not exist
messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
"address.message.edit.notexist"));
} else {
// delete object
clientsDAO.delete(cid);

// save messages
messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
"clients.message.delete.success"));
}
saveErrors(request, messages);
List list=clientsDAO.findAll();
request.setAttribute("clientsList", list);
return mapping.findForward("list");
}
}

#3



Clients.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="com.bookstoreonline.hibernate.beans.Clients" table="clients" catalog="bookstore">
        <id name="cid" type="java.lang.Integer">
            <column name="cid" />
            <generator class="native" />
        </id>
        <property name="cname" type="java.lang.String">
            <column name="cname" />
        </property>
        <property name="sex" type="java.lang.String">
            <column name="sex" />
        </property>
        <property name="phone" type="java.lang.String">
            <column name="phone" />
        </property>
        <property name="address" type="java.lang.String">
            <column name="address" />
        </property>
        <property name="post" type="java.lang.String">
            <column name="post" />
        </property>
        <property name="email" type="java.lang.String">
            <column name="email" />
        </property>
    </class>
</hibernate-mapping>


struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">

<struts-config>
  <!--
  <data-sources>
<data-source type="org.apache.commons.dbcp.BasicDataSource">
<set-property property="driverClassName"
value="com.mysql.jdbc.Driver" />
<set-property property="url"
value="jdbc:mysql://localhost:3306/bookstore" />
<set-property property="username" value="root" />
<set-property property="password" value="00000000" />
<set-property property="maxActive" value="10" />
<set-property property="maxWait" value="5000" />
<set-property property="defaultAutoCommit" value="false" />
<set-property property="defaultReadOnly" value="false" />
<set-property property="validationQuery"
value="SELECT COUNT(*) FROM manages" />
</data-source>
  </data-sources>
  -->
  <form-beans>
<form-bean name="loginForm"
type="com.bookstoreonline.struts.forms.LoginForm">
</form-bean>
<form-bean name="clientsForm"
type="com.bookstoreonline.struts.forms.ClientsForm">
</form-bean>
  </form-beans>
  <global-exceptions />
  <global-forwards />
  <action-mappings>
<action path="/index" forward="/login.jsp" />
<action path="/welcome" forward="/welcome.jsp" />

<action path="/login" name="loginForm" scope="request"
type="org.springframework.web.struts.DelegatingActionProxy" input="/login.jsp">
<forward name="success" path="/welcome.jsp" />
<forward name="failure" path="/login.jsp" />
</action>

<action path="/logout"
type="org.springframework.web.struts.DelegatingActionProxy">
<forward name="logout" path="/login.jsp" />
</action>

<action path="/clients" parameter="method" name="pageForm" scope="request"
type="org.springframework.web.struts.DelegatingActionProxy">
<forward name="list" path="/clients.jsp" />
</action>
<action path="/clients_add" parameter="method" name="clientsForm" scope="request"
type="org.springframework.web.struts.DelegatingActionProxy"
input="/clients_add.jsp">
<forward name="list" path="/clients.jsp" />
<forward name="add" path="/clients_add.jsp" />
</action>
<action path="/clients_edit" parameter="method" name="clientsForm" scope="request"
type="org.springframework.web.struts.DelegatingActionProxy"
input="/clients_edit.jsp">
<forward name="list" path="/clients.jsp" />
<forward name="edit" path="/clients_edit.jsp" />
</action>
</action-mappings>
  <message-resources parameter="com.bookstoreonline.struts.resources.ApplicationResources" />
</struts-config>


applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/bookstore</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>00000000</value>
</property>
</bean>

<!-- �������� -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource">
<ref local="dataSource" />
</property>
</bean>

<!-- ����Hibernate -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref local="dataSource" />
</property>
<property name="mappingResources">
<list>
<value>com/bookstoreonline/hibernate/beans/Manages.hbm.xml</value>
<value>
com/bookstoreonline/hibernate/beans/Clients.hbm.xml
</value></list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>

<!-- ����DAO -->
<bean id="managesDAO" class="com.bookstoreonline.hibernate.dao.ManagesDAO">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
<bean id="clientsDAO" class="com.bookstoreonline.hibernate.dao.ClientsDAO">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>

<!-- ����DAO���� -->
<bean id="ManagesDAOProxy"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
<property name="target">
<ref local="managesDAO" />
</property>
<property name="transactionAttributes">
<props>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
<bean id="ClientsDAOProxy"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
<property name="target">
<ref local="clientsDAO" />
</property>
<property name="transactionAttributes">
<props>
<prop key="insert">PROPAGATION_REQUIRED</prop>
<prop key="update">PROPAGATION_REQUIRED</prop>
<prop key="delete">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>

<!-- ����Struts���� -->
<bean name="/login" class="com.bookstoreonline.struts.actions.LoginAction">
<property name="managesDAO">
<ref local="managesDAO" />
</property>
</bean>
<bean name="/logout" class="com.bookstoreonline.struts.actions.LogoutAction">
<property name="managesDAO">
<ref local="managesDAO" />
</property>
</bean>
<bean name="/clients"
class="com.bookstoreonline.struts.actions.ClientsAction">
<property name="clientsDAO">
<ref local="clientsDAO" />
</property>
</bean>
<bean name="/clients_add"
class="com.bookstoreonline.struts.actions.ClientsAction">
<property name="clientsDAO">
<ref local="clientsDAO" />
</property>
</bean>
<bean name="/clients_edit"
class="com.bookstoreonline.struts.actions.ClientsAction">
<property name="clientsDAO">
<ref local="clientsDAO" />
</property>
</bean>
</beans>

#4


在web.xml中配置这个就行了啊!
<!-- 中文乱码处理 -->
  <filter>
  <filter-name>filter</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>

#5


进来学习学习!

#6


顶四楼,加一个SPRING的过滤器.还有不要忘记页面编码和服务器的编码要一致

#7


关注中。。。

#8


引用 4 楼 pengpeng409 的回复:
在web.xml中配置这个就行了啊! 
<!-- 中文乱码处理 --> 
  <filter> 
  <filter-name>filter </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> 
   <filter-name>filter</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>filter</filter-name>  
   <servlet-name>/*</servlet-name>  
  </filter-mapping> 

可是仍然是乱码,楼上说的页面编码和服务器的编码要一致,服务器编码是指哪个啊?

我在加了这么一段之后,其他地方的编码需要改动么,我现在还是保留UTF-8

另外可不可能是post方式提交或request、response的问题呢,我对**FORM获取表单内容的过程不太清楚,它是如何根据名称获取的呢

#9


补充一句,ClientsAction.java 中的insert方法,被注释掉的方法是正常的读取表单内容然后写入数据库中的代码,我为了测试是不是写入数据库的过程中出现了问题,所以将其注释而用指定的中文数据插入测试,结果插入的数据是乱码说明这个过程有问题

然后在ClientsForm.java 中,validate方法里加了一句 System.out.println("prince1:"+this.getCname());这是想测试ClientsForm接收表单数据的过程中是否有问题,结果输出的结果也是乱码,说明这个过程也有问题
那该怎么解决呢?

#10


表单提交都是通过servlet调post()或get()方法处理的,再把结果返回到客户端。
有做过滤器吗,写个过滤类,表单提交都先到servlet请求,如果在请求前加个过滤器,将字符都转为中文再进行处理。
public void doFilter(ServletRequest request, ServletResponse response, 
FilterChain chain) throws IOException, ServletException { 

HttpServletRequest request_1 = (HttpServletRequest) request; 
HttpServletResponse response_1 = (HttpServletResponse) response; 

// 转换编码,并且加上去缓存 
request_1.setCharacterEncoding("GBK"); 
response_1.setCharacterEncoding("GBK"); 
chain.doFilter(request, response); 


#11


前台后台服务器都要统一,你的过滤器里怎么是GBK?应该用UTF-8吧

#12


页面上的只是显示的编码吧,并不是请求的编码,后台和request的字符集保持一致就行,
前台页面和查询结果的字符集保持一致

#13


引用 10 楼 fafuhefan 的回复:
表单提交都是通过servlet调post()或get()方法处理的,再把结果返回到客户端。 
有做过滤器吗,写个过滤类,表单提交都先到servlet请求,如果在请求前加个过滤器,将字符都转为中文再进行处理。 

Java codepublic void doFilter(ServletRequest request, ServletResponse response, 
FilterChain chain) throws IOException, ServletException { 

HttpServletRequest request_1 = (HttpServletRequest) request; 
HttpSe…


我加了这么一个过滤器,按11楼说的都统一改成UTF-8
结果是表单提交数据到ACTION FORM是正确的,但是ACTIONFORM数据写入数据库的中文还是不正确,一个汉字变成了两个问号

#14


呵呵
这个乱码的问题我见到的比较多
你可以写个过滤器很简单的
源码青加QQ群76208671

#15



由于Java默认的编码方式是UNICODE,所以用中文易出问题,常用解决:
String s2 = new String(s1.getBytes(“ISO-8859-1”),”GBK”);

utf-8解决JSP中文乱码问题,在页面的开始处加:
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <%request.setCharacterEncoding("UTF-8");%>

如果仍不能解决问题,还需要这样处理一下:
String msg = request.getParameter("message");
String str=new String(msg.getBytes("ISO-8859-1"),"UTF-8");out.println(st); 

#16


找到问题的原因了,后来的写数据库的乱码问题是数据库设置没有设置编码

我在applicationcontext.xml中的数据库设置为

 </property>
        <property name="url">
        <value>jdbc:mysql://localhost:3306/bookstore</value>
 </property>

现在改成jdbc:mysql://localhost:3306/bbs?useUnicode=true&amp;characterEncoding=utf-8 就没有问题了

这样从页面到服务器到数据库都是统一的UTF-8编码了

#17


所以说对于中文问题,一个是用过滤器过滤传递过程的编码,再一个还是要注意数据库编码