Java Web coding problem Three: URL and URI and querystring encoding problem

Source: Internet
Author: User
Tags to domain

before the question, let's take a look at what is Url,uri and QueryString, as shown in 1:

Figure 1:url-uri-querystring

URL: is the acronym for the Global Resource Locator, as above localhost: refers to domain (IP or hostname), 8080: is the port Web service is generally 80,8080 is the use of its own test, to avoid and browser port conflicts.
ROOT: Is the Contentpath, which is the virtual path, if the Tomcat server object is the <context path= "/root" in the Servlet.xml configuration file/> If this tomcat is not configured, the default is path is root.
Servlet: Is the Servletpath message, which corresponds to the <url-pattern> in Web. XML, and is used to find the servlet.
Getspecialinfos: Is the file to be requested.
category= Native: It is querystring, equivalent to the parameters that are submitted with get.
Uri (Universal Resource Identifier, referred to as "uri"): Is every resource available on the Web. Locate through the URI. It is generally used by the server itself.

Now that we know Url,uri and querystring, we can try out their coding problems, see the following Java servlet program:

import java.io.ioexception;import javax.servlet.servletexception;import  javax.servlet.http.httpservlet;import javax.servlet.http.httpservletrequest;import  javax.servlet.http.httpservletresponse;import org.apache.logging.log4j.logmanager;import  org.apache.logging.log4j.logger;import org.wl.util.specialinfotojson;import org.wl.util.stringutils;  /** * servlet implementation class getspecialinfo */public class  GetSpecialInfos extends HttpServlet {          private static final long serialVersionUID = 1L;     Private static final logger log = logmanager.getlogger ();      /**     *  @see  httpservlet#httpservlet ()       */    public getspecialinfos () &NBSP;{&NBSP;&NBsp;      super ();         // todo  Auto-generated constructor stub    }           /**          *  @see   Httpservlet#doget (Httpservletrequest request, httpservletresponse response)            */         protected  void doget (Httpservletrequest request, httpservletresponse response)  throws  ServletException, IOException {                    dopost (Request, response);          }          /**           *  @see  httpservlet#dopost (httpservletrequest request, httpservletresponse  Response)           */          protected void dopost (httpservletrequest request, httpservletresponse  response)  throws ServletException, IOException {                    response.setcontenttype ("text/ Html;charset=utf-8 ");                                       log.info (Request.getcharacterencoding ());                    request.setcharacterencoding (" Utf-8 ");    &nbsP;               log.info ( Request.getcharacterencoding ());                   log.info (Request.getquerystring ());                    system.out.println ();                    string  category = request.getparameter ("category");                    if (Stringutils.isnullorempty (category))                     {                        &nbSp;    response.getwriter (). Append ("Category is null");                              return;                    }                    log.info (category);//                category = new string ( Category.getbytes ("Iso-8859-1"), "Utf-8");//                category = new string (Category.getbytes ("iso-8859-1"), "GBK");//                log.info (category);        &Nbsp;           response.getwriter (). Append ( Specialinfotojson.getcategoryinfo (category));          }}

I use a tomcat server, if you want to do a simple test, you can change the log statement to SYSTEM.OUT.PRINTLN (), output directly to the console, to avoid configuration log4j2. The last Response.getwriter (). Append (Specialinfotojson.getcategoryinfo) can be removed.

Direct access via browser: http://localhost:8080/market/GetSpecialInfos?category= native

Change the market to your project name.

Access the console output via IE browser:

Null

22:02:58.492 INFO Org.wl.app.GetSpecialInfos Dopost-utf-8

22:02:58.492 INFO Org.wl.app.GetSpecialInfos Dopost-category=íáì?2ú

22:02:58.492 INFO Org.wl.app.GetSpecialInfos doPost-íáì?2ú

Accessing the console's output via Firefox or Google Chrome (ignoring partial output):

Null

Utf-8

Category=%e5%9c%9f%e7%89%b9%e4%ba%a7

????? 1?o§

now it's time to guess what it means, it's all right. Let's put the commented out code first.

Category = New String (category.getbytes ("iso-8859-1"), "Utf-8"), remove comment, and run again.

Find the output of the console accessed using Firefox or Google Chrome as:

Null

Utf-8

Category=%e5%9c%9f%e7%89%b9%e4%ba%a7

????? 1?o§

Native

Use IE to access the console output as:

Null

22:43:56.614 INFO Org.wl.app.GetSpecialInfos Dopost-utf-8

22:43:56.614 INFO Org.wl.app.GetSpecialInfos Dopost-category=íáì?2ú

22:43:56.614 INFO Org.wl.app.GetSpecialInfos doPost-íáì?2ú

22:43:56.614 INFO Org.wl.app.GetSpecialInfos doPost- ??? ? ?

explains that the encoding format for QueryString is utf-8 for Firefox and Google. and IE for QueryString encoding is certainly not utf-8.

We are putting category = new String (category.getbytes ("iso-8859-1"), "Utf-8"); comment out.

put category = new String (category.getbytes ("iso-8859-1"), "GBK"); comments are removed. Re-run and then through IE

Firefox, andGoogle Chrome to access it.

the output of the console is IE Normal,Firefox and Google garbled. Description IE is GBK or compatible with the encoding (gb2312 , etc.)

the the QueryString is encoded.

Let's take a look at this sentence again:category = new String (category.getbytes ("iso-8859-1"), "Utf-8");

Why should weCategory.getbytes ("Iso-8859-1"), withIso-8859-1This code to get a byte array. is because forQueryString, if there is no in-Request header (Header) set inContentType, inTomcatof theServlet.xmlthe configuration file is not set<connector uriencoding= "Utf-8" uesbodyencodingforuri= "true"/>such a configuration. Then you will useIso-8859-1theQueryStringto encode. of ourRequest.setcharacterencoding ("Utf-8");This sentence has been output isNull, stating that the browser is not setContentType. We have not configured the server, so we are usingIso-8859-1theQueryStringthe encoding to be made.

at the same time we found request.setcharacterencoding ("Utf-8"); This does not seem to work, and it does not work for Get methods (including,URL parameters, and forms submitted through the Get method), but is used for post submissions. If you are interested, you can try it.

Note: You must set both ContentType and uesbodyencodingforuri= "true" to use ContentType in a way that is like decoding the querystring.


Java Web coding problem Three: URL and Uri and querystring encoding problems

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.