Use the filter filter to set the encoding format of post and get[key]

First quote the idea of ​​​​the big guy:  use the filter filter to set the encoding format


post encoding is easy:

1. In the XML configuration file

<filter>
  	<filter-name>Hello</filter-name>
  	<filter-class>com.jde.filter.HelloFilter</filter-class>
  	<init-param>
  		<param-name>encode</param-name>
  		<param-value>UTF-8</param-value>
  	</init-param>
  </filter>

2. Then in the filter method init()

The configured encoding UTF-8 can be obtained through filterConfig.getFilterName()

//String name = filterConfig.getFilterName();
		//Get the specified encoding configured in XML---->trim() cuts whitespace characters.
		String encode = filterConfig.getInitParameter("encode").trim();
		//If encode is not empty, let him assign a value
		if(encode != null && !"".equals(encode)){
			this.encode = encode;
		}

3. If you want to modify the encoding of the get request method, you need to create a class inheritance: HttpServletRequestWrapper

Need to override the getParameter() method!


Likewise, you can create a multi-argument constructor.

@Override
	public String getParameter(String name) {
		//The parent class getParameter is called to get the passed parameters
		String value = super.getParameter(name);
		
		/*
		 * 1. Start transcoding,
		 * 2. Define an intermediate variable valueLast
		 */
		String valueLast = null;
		
		//Assign valueLast
		try {
			/*
			 * Determine whether value is null,
			 * If it is null, then assign null to valueLast,
			 * If not, decode the content of value with ISO-8859-1, and then use UTF-8 to return a string to valueLast after encoding
			 */
			valueLast = value==null?null:new String(value.getBytes("ISO-8859-1"),encode);
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace ();
		}


4. Then it is to be configured in the doFilter() method, if it is the post method directly

//Set the post method to modify the code of the whole station
		request.setCharacterEncoding(this.encode);

If the request method is: get

Then you need:

if("get".equalsIgnoreCase(method)){
			
			//Create request decoration implementation class
			req = new myW(req,this.encode);
		}
		System.out.println("chain agrees to execute downward!");
		chain.doFilter(req, response);

....

OK---

Paste the entire code:

jsp code:,

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
  <h1>Use post to send data</h1>
    <form action="/HelloFilter/servlet/HelloServlet" method="post">
    	姓名:<input name="username" type="text">
    	<input type="submit" value="提交">
    </form>
	<h1>Use get to send data</h1>    
    
    <a href="/HelloFilter/servlet/HelloServlet?username=Hello everyone">Click</a>
  </body>
</html>

Code for the HttpServletRequestWrapper subclass:

package com.jde.filter;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class myW extends HttpServletRequestWrapper {
	//Set the default encoding property of the request decorator
	private String encode;
	// no-argument constructor
	public myW(HttpServletRequest request) {
		super(request);
	}
	//Define a parameterized constructor
	public myW(HttpServletRequest request, String encode) {
		super(request);
		this.encode = encode;
	}
	/*
	 * Override getparameter
	 */
	@Override
	public String getParameter(String name) {
		//The parent class getParameter is called to get the passed parameters
		String value = super.getParameter(name);
		
		/*
		 * 1. Start transcoding,
		 * 2. Define an intermediate variable valueLast
		 */
		String valueLast = null;
		
		//Assign valueLast
		try {
			/*
			 * Determine whether value is null,
			 * If it is null, then assign null to valueLast,
			 * If not, decode the content of value with ISO-8859-1, and then use UTF-8 to return a string to valueLast after encoding
			 */
			valueLast = value==null?null:new String(value.getBytes("ISO-8859-1"),encode);
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace ();
		}
		return valueLast;
	}
	
	
	
	
	

}

filter code:

package com.jde.filter;

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 HelloFilter implements Filter {
	
	private String encode;
	//log out
	public void destroy() {
	}
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		System.out.println("start....");
		
		//Set the post method to modify the code of the whole station
		request.setCharacterEncoding(this.encode);
		
		/*
		 * Now force the request method
		 */
		HttpServletRequest req = (HttpServletRequest)request;
		
		//Get the request method, whether it is get or post
		String method = req.getMethod();
		
		System.out.println("Print request method: "+method);
		
		/*
		 * 1. If the request method is get, enter it and start to set the encoding method of get
		 * 2. Case insensitive when comparing
		 */
		if("get".equalsIgnoreCase(method)){
			
			//Create request decoration implementation class
			req = new myW(req,this.encode);
		}
		System.out.println("chain agrees to execute downward!");
		chain.doFilter(req, response);
		
		
	}
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("Filter was created...");
		//String name = filterConfig.getFilterName();
		//Get the specified encoding configured in XML---->trim() cuts whitespace characters.
		String encode = filterConfig.getInitParameter("encode").trim();
		//If encode is not empty, let him assign a value
		if(encode != null && !"".equals(encode)){
			this.encode = encode;
		}
	}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325931491&siteId=291194637