jsp mysql解决中文乱码问题

最近在用struts1.x 和jsp开发web应用程序,后台数据库用的是mysql5,数据库编码是utf-8,jsp页面编码也使用了UTF-8,但是写入数据和读出来的中文总是乱码,很是困惑!参考了一些资料写了一个过滤器解决了问题

1.建立字符过滤器类SetCodeFilter,该类实现了javax.servlet.Filter接口

package com.sims.core; 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; import javax.servlet.http.HttpServletRequest; public class SetCodeFilter implements Filter { public void destroy() {} public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterchain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest)request; req.setCharacterEncoding("UTF-8"); filterchain.doFilter(request, response); } public void init(FilterConfig arg0) throws ServletException {} }

2.在web.xml中配置过滤器

<filter> <filter-name>setCodeFilter</filter-name> <filter-class>com.sims.core.SetCodeFilter</filter-class> </filter> <filter-mapping> <filter-name>setCodeFilter</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping> <filter-mapping> <filter-name>setCodeFilter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping>

你可能感兴趣的:(jsp,mysql,数据库,struts,filter,Class)