During java Development, garbled characters such as filter and filter are transmitted from the front-end to the backend.

Source: Internet
Author: User

During java Development, garbled characters such as filter and filter are transmitted from the front-end to the backend.

In enterprise development, the most common one is javaweb projects. When there are web projects, they will inevitably deal with the background. For example, I send new requests from jsp pages to the background, the backend may be servlet, struts2, springmvc, etc. In this case, there is a problem. If the sent parameter values contain Chinese characters, you will often find garbled characters in the backend, of course, you can re-encode the value after getting the value in the background, but it will be very troublesome if you re-encode it every time. Here we will introduce a simple method and hope it will be useful to you.


Filter is called a filter. It is a java servlet technology. With filter, We can filter the resources of the web server to be accessed, for example,

We can see that after the filter is added, you must use the filter to access the web resources. If there is no filter, you can directly access the web resources. This is the role of the filter, that is, you can control the access to resources. For example, you can monitor the url of user access to prohibit access by Unlogged users. Of course, there is also a key point, that is, you can filter character sets. Now, go to the topic.

Filter Development

There are two steps to develop a filter:

1. Compile a java class to implement the javax. servlet. Filter interface.

2. Register a filter

Compile the filter implementation class

I. The filter interface has three methods: init, destory, and doFilter.


When a filter is created, the web server is responsible for the creation of the filter. When the web server is started, the filter is created, and the init method of the filter is executed, because the filter is created only once, therefore, the init method is called only once. In this method, you can obtain the initialization parameters during registration through FilterConfig. The following methods are provided:

String getFilterName (): Get the filter Name.
String getInitParameter (String name): return the value of the initialization parameter specified in the deployment description. If no data exists, null is returned.
Enumeration getInitParameterNames (): returns an Enumeration set of the names of all initialization parameters of the filter.
Public ServletContext getServletContext (): return the reference of the Servlet context object.


The web server calls the destory method to destroy the filter. In the lifecycle of the filter, this method is executed only once. The user releases the resources used in the filter, such as database connections.


This method is the key to the entire filter, and our work is mainly done in this method. This method provides three parameters: ServletRequest req, ServletResponse resp,
FilterChain chain; the chain parameter is the filter chain. If we want to continue the request, we must call chain. doFilter method, so that the request will be passed down. We can choose when to call the chain according to our business. doFilter method.

2. Register a filter

Registering a filter is to let the web server know the filter and make the filter take effect. You need to register the filter in web. xml. For details about how to register the filter, refer to the following example.

Character Filter

The filter code is as follows:

1 package com.cn. imooc. filter; 2 3 import java. io. IOException; 4 5 import javax. servlet. filter; 6 import javax. servlet. filterChain; 7 import javax. servlet. filterConfig; 8 import javax. servlet. servletException; 9 import javax. servlet. servletRequest; 10 import javax. servlet. servletResponse; 11 import javax. servlet. http. httpServletRequest; 12 import javax. servlet. http. httpServletResponse; 13 14 public class SetCharacterEncodingFilter implements Filter {15 16 // storage encoding format information 17 private String encode = null; 18 @ Override19 public void destroy () {20 // TODO Auto-generated method stub21 22} 23 24 @ Override25 public void doFilter (ServletRequest req, ServletResponse resp, 26 FilterChain chain) throws IOException, servletException {27 // TODO Auto-generated method stub28 29 // convert 30 HttpServletRequest request = (HttpServletRequest) req; 31 HttpServletResponse response = (HttpServletResponse) resp; 32 33/* 34 * judgment on the web. whether the encoding format is configured in the xml file 35 * if it is null, set the encoding format to 36 * in the configuration file; otherwise, set the encoding format to UTF-8.
37 */38 if (this. encode! = Null &&! This. encode. equals ("") {39 request. setCharacterEncoding (this. encode); 40 response. setCharacterEncoding (this. encode); 41} else {42 request. setCharacterEncoding ("UTF-8"); 43 response. setCharacterEncoding ("UTF-8"); 44} 45 46/* 47 * use the doFilter method to call the next filter or target resource (servlet or JSP page) in the chain ). 48 * chain. doFilter processes the remaining part of the filter (if any) and finally processes the requested servlet or JSP page. 49 */50 chain. doFilter (request, response); 51 52} 53 54 @ Override55 public void init (FilterConfig arg0) throws ServletException {56 // TODO Auto-generated method stub57 58 this. encode = arg0.getInitParameter ("encode"); 59 System. out. println ("this. encode: "+ encode); 60} 61 62}

Obtain the configured initialization parameter "encode" in the init method, convert the request to httpSerevletRequest and HttpServletResponse, set the encoding, and finally call the chain. the doFilter (request, response) method to filter the encoding.

Register the filter as follows in web. xml:

1 <! -- Filter configuration information --> 2 <filter> 3 <filter-name> SetCharacterEncodingFilter </filter-name> 4 <! -- Filter encoding file --> 5 <filter-class> com.cn. imooc. filter. SetCharacterEncodingFilter </filter-class> 6 <init-param> 7 <! -- Init-param defines the initialization parameters of the filter --> 8 <description> set the name and encoding type for the parameters and values </description> 9 <param-name> encode </param- name> 10 <param-value> UTF-8 </param-value> 11 </init-param> 12 </filter> 13 <filter-mapping> 14 <! -- Filter-mapping tells the container that all requests matching the pattern should be allowed through the access control filter. 15. all accesses ended with an action are first filtered through the filter file --> 16 <filter-name> SetCharacterEncodingFilter </filter-name> 17 <url-pattern> *. action </url-pattern> 18 </filter-mapping>

When registering the filter, we configured the initialization parameter to UTF-8 and set it in the intercepted url to intercept all url requests ending with action.

With the above code, you can set the Request Encoding

Thank you!


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.