struts 表单中文乱码问题

 

今天被这个问题给搞晕了,因为之前遇到这个问题很容易解决了,今天试了很多方法度没有解决,网上一般是用filter和扩展struts的ActionServlet的process方法来解决的,我用了一下,但是为了便于以后查看,就记一下:

方法一:filter

 

 

package cn.edu.hbmy.com.thesis.web;
 
import java.io.IOException;
 
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
 
public class EncodingFilter implements Filter {
private String encoding;
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
request.setCharacterEncoding(encoding);
filterChain.doFilter(request, response);
}
public void init(FilterConfig config) throws ServletException {
encoding = config.getInitParameter("encoding");
}
}

 
web.xml:

 

<filter>
   <filter-name>Encodeing</filter-name>
   <filter-class>cn.edu.hbmy.com.thesis.web.EncodingFilter</filter-class>
  <init-param>
  <param-name>encoding</param-name>
  <param-value>UTF-8</param-value>
  </init-param>
   </filter>
 
<filter-mapping>
<filter-name>Encodeing</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
 

 

方法2:扩展struts的ActionServlet的process方法

 

 

 

public class MyActionServlet extends ActionServlet {
private static final long serialVersionUID = 1L;
 
 
@Override
protected void process(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
super.process(request, response);
}
}

  web.xml:

 

<servlet>     
    <servlet-name>action</servlet-name>
    <servlet-class>cn.edu.hbmy.com.thesis.web.MyActionServlet</servlet-class>
    <init-param>  
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <init-param>
      <param-name>debug</param-name>
      <param-value>2</param-value>  
    </init-param>  
    <init-param>
      <param-name>detail</param-name>
      <param-value>2</param-value>
    </init-param>
    <load-on-startup>0</load-on-startup>
  </servlet>
  

 

你可能感兴趣的:(struts)