1. 程式人生 > >java 出現亂碼如何解決

java 出現亂碼如何解決

(一)post
        [1]通過request.setCharacterEncodeing("UTF-8");
        [2]通過String name = new String(request.getParameter("name").getBytes("ios8859-1"),"utf-8")
        [3]在web.xml配置一個過濾器filter
        [4]如果是spring ,在web.xml配置一個過濾器:org.springframework.web.filter.CharacterEncodingFilter

        [5Struts2]待看

(二)get
        [1]在tomcat中servlet.xml中增加URIEncoding="UTF-8"
        [2]用上面的通過String name = new String(request.getParameter("name").getBytes("ios8859-1"),"utf-8")

程式碼實現(註釋部分為實現的)

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>測試</title>
</head>
<body>

	<form action="login" method="get">
		<table align="center">
			<tr>
				<td>使用者名稱: <input type="text" name="username"></input></td>
			</tr>
			<tr>
				<td>密碼:   <input type="password" name="password"></input>
				</td>
			</tr>
			<tr>
				<td align="center"><input type="submit" value="登陸"></input></td>
			</tr>
		</table>
	</form>

</body>
</html>


web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<servlet>
		<servlet-name>Login</servlet-name>
		<servlet-class>com.ay.login.LoginServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>Login</servlet-name>
		<url-pattern>/login</url-pattern>
	</servlet-mapping>
	<welcome-file-list>
		<welcome-file>login.jsp</welcome-file>
	</welcome-file-list>

	<!-- <filter>
		<filter-name>encoding</filter-name>
		<filter-class>com.ay.login.SetCharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>utf-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping> -->

	<!-- 使用spring作為過濾器, -->
	<!--<filter> -->
		<!-- 過濾器使用spring類CharacterEncodingFilter -->
	<!--	<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name> -->
			<!-- 過濾器過濾後的編碼為utf-8 -->
		<!--	<param-value>utf-8</param-value>
		</init-param>
	</filter>
	<filter-mapping> -->
		<!-- 過濾所有的路徑:/*代表所有的路徑 -->
		<!--<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping> -->


</web-app>

    

filter

package com.ay.login;


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 SetCharacterEncodingFilter implements Filter {

   /**
    * The default character encoding to set for requests that pass through
    * this filter.
    */
   protected String encoding = null;

   /**
    * The filter configuration object we are associated with.  If this value
    * is null, this filter instance is not currently configured.
    */
   protected FilterConfig filterConfig = null;

   /**
    * Should a character encoding specified by the client be ignored?
    */
   protected boolean ignore = true;

   public void destroy() {
       this.encoding = null;
       this.filterConfig = null;
   }

   public void doFilter(ServletRequest request, ServletResponse response,
                        FilterChain chain) throws IOException, ServletException {

       // Conditionally select and set the character encoding to be used
	   System.out.println("encoding1->"+encoding);
       if (ignore || (request.getCharacterEncoding() == null)) {
           String encoding = selectEncoding(request);
           if (encoding != null)
               request.setCharacterEncoding(encoding);
       }

       chain.doFilter(request, response);

   }

   /**
    * Place this filter into service.
    * @param filterConfig The filter configuration object
    */
   public void init(FilterConfig filterConfig) throws ServletException {
	   System.out.println("encoding2"+encoding);
       this.filterConfig = filterConfig;
       this.encoding = filterConfig.getInitParameter("encoding");
       String value = filterConfig.getInitParameter("ignore");
       if (value == null)
           this.ignore = true;
       else if (value.equalsIgnoreCase("true"))
           this.ignore = true;
       else if (value.equalsIgnoreCase("yes"))
           this.ignore = true;
       else
           this.ignore = false;

   }

   protected String selectEncoding(ServletRequest request) {
       return (this.encoding);
   }

}

src 處理輸出程式碼
package com.ay.login;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet{
	
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    	//一、post
////    		//1.設定編碼格式
////    		request.setCharacterEncoding("UTF-8");
//            System.out.println("登陸");
//            String name=request.getParameter("username");
//            String password=request.getParameter("password");
//            //2.通過getBtyes("ios8859-1")轉化成“UTF-8”
////            String uname = new String(name.getBytes("iso8859-1"),"UTF-8");
////            System.out.println("uname:"+uname);
//            //3.增加一個過濾器Filter(自己寫的)
//            System.out.println("使用者名稱:"+name);
//            System.out.println("密碼:"+password);
//            //4.如果用Struts,以後會專門寫一下關於Struts2如何解決亂碼
//            //5.若使用了spring也簡單,配置一個spring中提供的攔截器:
        //二、get
    	//1.通過getBtyes("ios8859-1")轉化成“UTF-8”
    	String name=request.getParameter("username");
    	String password=request.getParameter("password");
//    	String uname = new String(name.getBytes("iso8859-1"),"UTF-8");
//    	System.out.println("uname:"+uname);
    	System.out.println("使用者名稱:"+name);
    	System.out.println("密碼:"+password);
    	//2.設定tomcat伺服器的server.xml這個檔案,找到下面的這個段程式碼,新增上URIEncoding="UTF-8",在下面這個配置中
    	//<connector URIEncoding="UTF-8" redirectPort="8443" protocol="HTTP/1.1" port="8080" connectionTimeout 

    	
            
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }

}