In JSP, sometimes appear in the submission of garbled, so how to solve? \

\

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 submitted a garble problem
		request.setCharacterEncoding("utf-8");
		
		// Get the data from the hyperlink
		System.out.println("----- get the data passed by the hyperlink -----");
		String name = request.getParameter("name");
		String pwd = request.getParameter("password");
		System.out.println(name);
		System.out.println(pwd);
		
		
		System.out.println("----- Get the data passed from the form -----");
		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++) {

		
			// If it is a GET submission, handle garbled characters
			String hb = hobbys[i];
			// Convert Chinese to bytes
			byte[] ch = hb.getBytes("iso-8859-1"); System.out.println(Arrays.toString(ch)); .// Combine the bytes with the specified encoding
			String str = new String(ch,"utf-8");


			// Or the shorthand is
	//String str=new String(request.getParameter("nickname").getBytes("ISO-8859-1"),"utf-8");
			
			System.out.println(str);


	/* * Add URIEncoding=" UTF-8 "to the *Connector tag in the server.xml file of the server. *
       * */}}}Copy the code


\

\

There are other solutions available on the web, such as adding coding filters (as in Spring), or custom coding filters, etc. :

Coding filters in Spring<! -- Encoding filter -->
<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>
Copy the code

\