zoukankan      html  css  js  c++  java
  • JSP中文乱码问题(get,post篇)

    在JSP中,有时在提交时会出现乱码,
    那么如何让解决呢?


    public class RequsetDemo2 extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doPost(request, response);
    	}
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    
    
    		//post提交的乱码问题
    		request.setCharacterEncoding("utf-8");
    		
    		//获取超链接传递过来的数据
    		System.out.println("-----获取超链接传递过来的数据-----");
    		String name = request.getParameter("name");
    		String pwd = request.getParameter("password");
    		System.out.println(name);
    		System.out.println(pwd);
    		
    		
    		System.out.println("-----获取表单传递过来的数据-----");
    		String nickname = request.getParameter("nickname");
    		System.out.println(nickname);
    		
    		String[] hobbys = request.getParameterValues("hobby");
    		//System.out.println(Arrays.toString(hobbys));
    		for (int i = 0; i < hobbys.length; i++) {
    
    		
    			//如果是get提交,处理乱码问题
    			String hb = hobbys[i];
    			//把中文转换成字节
    			byte[] ch = hb.getBytes("iso-8859-1");
    			
    			System.out.println(Arrays.toString(ch));.
    			//再把字节以指定编码组合
    			String str = new String(ch,"utf-8");
    
    
    			//或者简写为
    	//String str=new String(request.getParameter("nickname").getBytes("ISO-8859-1"),"utf-8");
    			
    			System.out.println(str);
    
    
    	/*
    	*或者服务器的server.xml中的
    	*Connector标签中添加URIEncoding="utf-8(也就是设置端口的那一个标签).
    	*如下
    	*<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="utf-8"/>
    	*
    	*/	}
    		
    		
    		
    	}
    
    }



    在网上也有其他的解决方式,比如添加编码过滤器(如spring中的),又或是自定义编码过滤器等等:

    Spring中的编码过滤器  
      <!-- 编码过滤器 -->
    <filter>
       <filter-name>Spring character encoding filter</filter-name>
       <filter-class>
        org.springframework.web.filter.CharacterEncodingFilter
       </filter-class>
       <init-param>
        <param-name>encoding</param-name>
        <param-value>gb2312</param-value>
       </init-param>
    </filter>
    <filter-mapping>
       <filter-name>Spring character encoding filter</filter-name>
       <url-pattern>/*</url-pattern>
    </filter-mapping>

  • 相关阅读:
    给大家介绍几个网站学习前端和服务器语言的网站吧,一定有合适你的
    centos用yum安装软件提示:另外一个程序锁定了 yum;等待它退出
    模仿小猎CMS首页功能展示的JS效果
    在centos下安装Node.js 开发环境搭建
    discuz在IIS,apache中分别怎么设置伪静态
    CentOS系统下各文件夹的作用
    centos上网设置
    php微信公众平台开发获取access_token,用CURL出现certificate verify failed错误的解决方法
    12.9 NIO
    12.8 Java 9改进的对象序列化
  • 原文地址:https://www.cnblogs.com/fonttian/p/7294870.html
Copyright © 2011-2022 走看看