jsp过滤器中文乱码解决

晨曦之光 发布于 2012/05/16 17:05
阅读 294
收藏 0



CharseterEncodingFilter1.java

private FilterConfig config = null;

private String defaultCharset = "utf-8";

 

public void doFilter(ServletRequest request, ServletResponse response,

           FilterChain chain) throws IOException, ServletException {

      

       HttpServletRequest req = (HttpServletRequest) request;

       HttpServletResponse resp = (HttpServletResponse) response;

      

       String charset = config.getInitParameter("charset");

       if(charset==null){

           charset = defaultCharset;

       }

       request.setCharacterEncoding(charset);

 

        //有时候response不用设置编码,因为servlet一般不做输出,

//输出交由jsp来做,所以只要jsp页面设定编码即可

       resp.setCharacterEncoding(charset);

       resp.setContentType("text/html;charset="+charset);

      

       chain.doFilter(req, resp);

 

}

 

public void init(FilterConfig filterConfig) throws ServletException {

       this.config = filterConfig;

}

Web.xml

    <filter>

       <filter-name>charseterEncodingFilter1</filter-name>

        <filter-class>cn.class3g.web.filter.CharseterEncodingFilter1</filter-class>

    </filter>

    <filter-mapping>

       <filter-name>charseterEncodingFilter1</filter-name>

       <url-pattern>/*</url-pattern>

    </filter-mapping>

 

Index.jsp

   <form action="/Filter_Test/servlet/TestCharsetServlet" method="post" >

   城市:<input type="text" name="city" value="保定"/> <br/>

   <input type="submit" value="提交" />

   </form>

TestCharsetServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String city = request.getParameter("city");

    response.getWriter().write(city);

}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String city = request.getParameter("city");

    response.getWriter().write(city);

}


l        将表单的method改为get再次测试,乱码。因为此种办法不能解决get方式的乱码问题


原文链接:http://blog.csdn.net/xy849288321/article/details/7004730
加载中
返回顶部
顶部