How to solve javaweb garbled problem

Source: Internet
Author: User
Tags form post

Being a qualified web developer should be a problem that has been encountered, especially garbled. Everyone may realize that, we Chinese learn programming, a big inconvenience is the coding problem of the program, no matter what technology to learn, we need to explore his coding problems.

Today to talk about the solution Javaweb garbled appearance of the reasons and solutions, welcome everyone to communicate correct.

First of all, the first clear two questions, why is there garbled? When do we get garbled when we write a web app?

The first question: Many beginners will find that when we write a Web application on our client, it is clearly a normal kanji, but when posted to the server, the browser will see garbled characters.

This problem occurs because the system default encoding in Chinese Windows system is GBK (everyone can enter the DOS window, input chcp to query), and when we write the Web app, myeclipse default encoding is usually iso8859-1, The browser will also have its own encoding options ... So many places use different codes, if two encoding does not correspond, of course, will appear garbled.

The second problem: garbled place can be attributed to three classes: 1. The basic JSP page is garbled, 2. The form is garbled, 3. Garbled database

The following is explained in turn:

1. Basic JSP page display garbled

This situation is relatively simple for beginners only, because the JSP page is saved, the conversion encoding and browser parsing is not the same. There are three solutions involved

1). <%@ page language= "java" pageencoding= "UTF-8"%> as we all know, the JSP is the servlet,jsp will be converted into a servlet after the conversion to the relevant Java code and then sent to the client.

Then there is a need for a statement in the JSP to control what encoding the JSP converts to the servlet. The above code is control, JSP is saved by UTF-8 encoding, that is to say, UTF-8 encoding way to the servlet.

2). <%@ page contenttype= "Text/html;charset=utf-8"%> familiar with the HTTP protocol friends are not unfamiliar with this code, charset= "UTF-8" is to set the response header encoding mode is UTF-8.

3). <meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "> The same sentence, except that this sentence uses HTML to control the browser parsing method.

Example:

We write this code in a simple JSP page with Chinese characters on the page, but default pageencoding= "Iso8859-1"

<%@ Page Language="Java"Import="java.util.*"pageencoding="iso8859-1"%><%StringPath=Request.getcontextpath ();StringBasePath=Request.getscheme ()+"://"+Request.getservername ()+":"+Request.getserverport ()+Path+"/";%><!DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en"><HTML>  <Head>    <title>My JSP ' index.jsp ' starting page</title>  </Head>  <Body>        <formAction= "encoding.jsp"Method= "Get">Username:<inputtype= "text"name= "Name" /><BR>Gender:<inputtype= "text"name= "Sex" /><BR>            <inputtype= "Submit"value= "Submit" />        </form>  </Body></HTML>

Page display:

HTTP Message Request Header:

All you have to do is follow the default encoding when you modify the response above.

2. Form submission garbled

When we use the form to submit Chinese, there will also be garbled, because the Tomcat server internal encoding by default, ISO8859-1,TOMCAT will use the default way of encoding iso8859-1 to parse Chinese.

When the form get is submitted, the server parses the submitted data with the default encoding and adds it to the next page after the URL.

Workaround: Configure the Server.xml file in the Tomcat server to include usebodyencodingforuri= "true" uriencoding= "UTF-8" in the connector node, This way the receiving page will be decoded using UTF-8.

When the form post is submitted, the submitted data is no longer added to the URL, and we can add a servlet filter to the Web app to set the encoding unity (the servlet filter executes before the relevant URL of the access settings).

Filter Related code:

 Public classConvertencodingImplementsFilter {PrivateString encoding; @Override Public voiddestroy () {} @Override Public voidDoFilter (servletrequest req, Servletresponse resp, filterchain chain)throwsIOException, Servletexception {req.setcharacterencoding (encoding);//Set Request EncodingResp.setcontenttype ("text/html;charset=" +encoding);//Setting the response encodingChain.dofilter (REQ,RESP); } @Override Public voidInit (filterconfig config)throwsservletexception { This. Encoding = Config.getinitparameter ("encoding");//Read the default encoding    }}

Related configuration Web. xml:

<Filter>        <Filter-name>Encoding</Filter-name>        <Filter-class>Filters.convertencoding</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>

This way we will find that even the data submitted by post is not garbled. 、

3. Database garbled

For most database JDBC drivers, the data passed between the Java program and the database is in iso8859-1 as the default encoding format, so when you store data that contains Chinese in the program to the database, The driver is limited to the program internal Unicode encoding format data conversion to ISO8859-1 encoding, and then passed to the database, if you want to solve the database garbled problem, the simplest is to change the database default encoding format.

Postscript:

About UTF-8 Encoding: UTF-8 encoding is written in uppercase and lowercase (alias UTF8 is required in MySQL database). The coded writing format is partially case-insensitive under Windows, but some Ides are strictly case-sensitive, and some friends may have met the IDE to tell you that Utf-8 and UTF-8 are not the same situation, it is very confusing to say, the parsing of the encoding format is case-sensitive, So we must write the code when writing.

How to solve javaweb garbled problem

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.