Chinese and related issues in J2EE Web components (4)

zhaozj2021-02-16  66

5. Using a filter

In practice, when we deal with client data, most of them are implemented in JavaBean, of course, can be blended in decoding in the session bean, but no one is willing to do this, and in fact we may have a lot of beans This approach is not allowed to maintain and update. We can also set up in JSPS / Servlets through servletRequest.setCharateRencoding (String Encoding), but it is also an annoying thing in many JSPS / servlets. The most ideal way is to be eternal and decoded only in one place, that is, in the filter. As long as the data submitted by the customer in the filter correctly, we don't worry about JSPS / servlets / javabeans. Our customers may be the mainland, or it may be Taiwan Province. That is to say, we have to worry about GB2312 and BIG5, the most ideal is to let them submit the data from UTF-8, then You don't have to decide Decoding, here we can use the fourth way to allow the server to affect the browser to select Encoding, which sets the Content-Type in the head, so that all JSP and Servlet's response entities are UTF-8, Then browser will also choose UTF-8 we use to encode submitted data.

Package filters;

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;

Import javax.servlet.http.httpservletRequest;

Public Class EncodingFilter Implements Filter

{

PRIVATE FILTERCONFIG CONFIG;

PRIVATE STRING DEFALUTENCODEING

Public void init (FilterConfig Config)

{

THIS.CONFIG = Config;

Defalutencodeing = config.getinitParameter ("encoding");

}

Public Void Dofilter (ServletRequest Request, ServletResponse Response,

Filterchain Chain) Throws oException, ServletException

{

Request.setCharacterencoding (Defalutencode);

String Uri = (httpservletRequest) Request .getRequesturi ();

IF (Uri.indexof (". jsp")! = -1 || Uri.indexof ("servlet")! = -1)

Response.setContentType ("text / html; charSet =" defalutencode;

System.out.println ("Filter Set The Encoding of the Response TO"

Response.getCharacterencoding ()); chain.dofilter (request, response);

}

Public void destroy ()

{

// ...

}

}

Configure the following configuration in the Web.xml of Context:

encoding filter

filters.encodingfilter

Encoding

UTF-8

encoding filter

/ *

It can be found with a Test.jsp test, and the browser's output is not as good as we expected, and the test.jsp source code is as follows:

<% @ Page PageEncoding = "GBK"%>

<% String str = "In JSP, the encoding has been set to:" response.getcharacterencoding ();

System.out.println (STR);%>

<% = STR%>

Its output is in Figure 3-3 and Figure 3-4, there is no way to garbled in the client, because we can find that in the filter through the output of the server, the encoding has been set to UTF-8, but In JSP, the encoding is also set to ISO-8859-1. With the filter, the JSP coding setting failed, so the output of JSP failed, we saw garbled.

Figure 3-3 Pre-setting coding failed to the filter for the filter

Figure 3-4 Server Output Description Code in JSP is also set to ISO8859-1

But a servlet code proves that the filter has been set up.

Import javax.servlet.http.httpservlet;

Import javax.servlet.http.httpservletRequest;

Import javax.servlet.http.httpservletResponse;

Import javax.servlet.servletException;

Import java.io.ioException;

Import java.io.printwriter;

Public class encoding extends httpservlet {

Protected Void Doget (HttpservletRequest Request, HttpservletResponse Response)

Throws servletexception, ioException {

PrintWriter out = response.getwriter ();

String str = "In servlet, the code is:" response.getcharacterencoding ();

System.out.println (STR);

Out.println (STR);

Out.flush ();

}

}

You can do experiments in the absence of a filter and without a filter, and the result should be found that the server side and the client get the output of the UTF-8 in the state of the filter. When there is no filter, the server The correct output encoding is ISO-8859-1, but the client outputs garbled, whether it is garbled or no filter servlet when JSP, these are understandable, because when there is no CONTENTTYPE instruction for JSP The JSP engine automatically set it to ISO-8859-1, and use ISO-8859-1 to encode Chinese, of course, only garbled. It is now possible to use a filter to set the response entity encoding to achieve the hope of the encoding of the control browser to submit data, no one will use servlet to output the form-containing HTML page. However, the coding code for setting the data submitted in the filter is still meaningful. For JSP, we can compromise to the ContentType in each JSP, perhaps define ContentType in a JSP file, and other JSP files are feasible to use the file to use the file.

<% - encoding.jsp -%>

<% @ Page ContentType = "Text / HTML; Charset = UTF-8"%>

Static

<% - form.jsp -%>

<% @ Page PageEncoding = "GBK"%>

<% @ include file = "encoding.jsp"%>

<% String name = request.getParameter ("name");%>

form </ title></p> <p></ hEAD></p> <p><body></p> <p><form method = "post" action = "test.jsp"></p> <p><label> Please enter your name </ label></p> <p><Input Type = "text" name = "name" size = "20"></p> <p><Input Type = "Submit" value = "Submit"></p> <p></ form></p> <p><% IF (name! = null&&! name.equals ("")) {</p> <p>//%> <p> Your name is: <% = Name%> </ p> <%</p> <p>}%></p> <p></ body></p> <p></ html></p> <p>Here, our decoding of the data submitted to the customer is done in the filter encoding filter. <% @ Page PageEncoding = "GBK"%> is not omitted into Encoding.jsp, which is clear that it is only valid for the JSP file that uses its, and does not pass to the included file in the include directive. Go.</p> <p>6. Chinese string of URI</p> <p>Typically, we will try our best to avoid non-English characters in the URI (Uniform Resource Indentifier, the Uniform Resource Identifier, Defined in RFC2396), but not all of them can be avoided, and this avoids increased our development. Cost or running efficiency. If you want to use the Chinese URL (Uniform Resource Locator, unified resource locator, defined in RFC1738, it is the subset of URI) to access Web resources on the server, that is not. For example: http: // localhost / I am Chinese .html</p> <p>Is it impossible to access "I am Chinese .html" on the server, because the browser (I use MSIE6.0B) will unconditionally with UTF-8 encoding:</p> <p>Http://localhost/我是中国人.html</p> <p>And the server uses the system default code to decode this URL, which is equivalent to execution.</p> <p>Java.net.urdecoder.Decoder (URL);</p> <p>This action. However, this method is not used to use (deprecated), but should use new methods</p> <p>Public String Decode (String Url, String Chars)</p> <p>The server uses the default GBK to decode the URI, but the browser is difficult to use GBK to encode URI, three of JavaScript has three global functions for encoding URIs.</p> <p>l Encodeuri (URI)</p> <p>l Encodeuricomponent (URI)</p> <p>l Escape (URI)</p> <p>The front two functions appear in IE5.5 , they use UTF-8 to encode the parameter URI and return to the encoded string; the last function is not used to use (deprecated), it directly uses "%" plus The Unicode internal code of the character is character, such as</p> <p>Escape ("I am Chinese") =% U6211% U662F% U4E2D% U56FD% U4EBA</p> <p>In this way, we have to encode the URI with java.net.urlencoder, such as</p> <p><% - encodeurl.jsp -%></p> <p><% String file = "I am Chinese .html";</p> <p>URL = java.net.urlencoder.Encode (File, "GBK");%></p> <p><a href="<%=url%> <% = file%> </A></p> <p>In this way, we have implemented a web file with Chinese characters in the file name. In fact, this is not much for the practice of adding costs, and sacrificing server efficiency. No one will deliberately use a Chinese file name.</p> <p>In HTTPSERVLETREQUEST, request query strings (obtained by method getQueryString () is not a URI (by way of getRequesturi (), is not a URL (by method getRequesturil (), server use When the URLDECoder decoded the URL, the slighter did not have an impact on it, and it can be said that it is handled, and the filter Encoding filter used in front.</p> <p>Request.setCharacterencoding (Defalutencode);</p> <p>It will have an impact on it. Let us look at an experiment, the experiment loads the filter Encoding Filter: <script></p> <p>// Browse not automatically encodes a non-English character in the query string</p> <p>Function encodinghref (obj)</p> <p>{</p> <p>Obj.href = encodeuri (obj.href);</p> <p>}</p> <p></ script></p> <p><a href="test.jsp?name= 胡zhou "οnclick="encodinghref(this )"> Go </A></p> <p>The source code of Test.jsp is as follows:</p> <p><% @ page contenttype = "text / html; charset = GBK"%></p> <p>Pathinfo = <% = Request.getPathInfo ()%> <br></p> <p>Pathtranslated = <% = request.getPathTranslated ()%> <br></p> <p>ContextPath = <% = Request.getContextPath ()%> <br></p> <p>QueryString = <% = Request.getQueryString ()%> <br></p> <p>Requesturi = <% = Request.getRequesturi ()%> <br></p> <p>RequestURL = <% = Request.getRequestURL ()%> <br></p> <p>servletPath = <% = Request.getServletPath ()%> <br></p> <p>Name = <% = Request.getParameter ("name")%></p> <p>Output is shown in Figure 3-5:</p> <p>Figure 3-5</p> <p>The result of the output is what we hope. We can also use JSP code on the server side:</p> <p><a href="test.jsp?name=<%=urlencoder.Encode ("Huzhou", "repent-8")"> Go </A></p> <p>Required request in advance</p> <p>URI</p> <p>,use</p> <p>JavaScript</p> <p>Code encoding query string and use</p> <p>JSP</p> <p>The code is compared, both have the longevity.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-23800.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="23800" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.051</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = '_2FhYC43dWtXWpfkUN7Y1dAE0hBuypyjlGnJ0ZhDZbi2mcrt_2BODylkVlbi_2FpOO_2B0y4Ug4nyR_2BKnyzoyTHjF4hl6Q_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>