关于JSP页面编码过滤器(注解配置)

在src下添加一个Filter过滤器

package com.kevin.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.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;

@WebFilter(filterName="encodingFilter",urlPatterns="/*")
public class EncodingFilter implements Filter {
	String encoding;
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
		chain.doFilter(request, response);

	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("destroy");
	}
}


主要为两点:

第一个就是注解的配置:@WebFilter(filterName="encodingFilter",urlPatterns="/*")

第二点就是在doFilter方法里指定格式(UTF-8举例):

request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);

你可能感兴趣的:(Javaweb)