乱码解决方法

如果用户是以get的方式进行请求数据是,那么,
 String s = req.getParameter("username");
String news =
new
String(s.getBytes("iso8859-1"
), "utf-8");
System.out.println(news);
可以解决乱码问题
如果用户是以post的方式进行请求数据时,那么,
 req.setCharacterEncoding("utf-8");// 只对post有效 即可
如果想对post的也有效那么,在tomcat服务器下面添加        useBodyEncodingForURI="true"
 
/**
     * @param req
     * @return 
     * @throws UnsupportedEncodingException
     * 想对get解决中文乱码,并且不重启服务器的方法
     * 只有当提交方式为get时方法可以起到作用
     */

    private String getEncode(HttpServletRequest req)
            throws UnsupportedEncodingException {
        /**
         * 如果想对get解决中文乱码,并且不重启服务器的方法
         * */

        String s = req.getParameter("username");
        String news = new String(s.getBytes("iso8859-1"), "utf-8");
        System.out.println(news);
        /**只有当提交方式为get时上面的方法可以起到作用*/
        return s;
    }
    要想让request.setCharacterEncoding("UTF-8")既支持get提交方式请求  也支持post提交方式请求
            则需要在tomcat/conf/server.xml文件中修改某个元素
                即<Connector port="80" protocol="HTTP/1.1"
                       connectionTimeout="20000"
                       redirectPort="8443" />
                       加上一个属性useBodyEncodingForURI="true"
                   使其变为
                       <Connector port="80" protocol="HTTP/1.1"
                           connectionTimeout="20000"
                           redirectPort="8443" useBodyEncodingForURI="true"/>




posted @ 2013-03-25 11:37  thero  阅读(175)  评论(0编辑  收藏  举报