当前位置 : 主页 > 编程语言 > java >

jsp字符编码过滤器的实现

来源:互联网 收集:自由互联 发布时间:2021-06-25
1.新建一个Dynamic Web Project项目,里面新建1个filter文件和1个jsp文件,整体的框架如图所示: 2.SetCharacterEncodingFilter.java里面的代码如下所示: package filter;import java.io.IOException;import javax.s

1.新建一个Dynamic Web Project项目,里面新建1个filter文件和1个jsp文件,整体的框架如图所示:



2.SetCharacterEncodingFilter.java里面的代码如下所示:

package 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 = "setCharacterEncodingFilter", urlPatterns = { "/*" }, initParams = { @WebInitParam(name = "encoding", value = "utf-8") })
public class SetCharacterEncodingFilter implements Filter {

	public static String encoding;

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		request.setCharacterEncoding(encoding);
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig fConfig) throws ServletException {
		encoding = fConfig.getInitParameter("encoding");
	}

}

3. one.jsp里面的代码如下所示:

<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>example</title>
</head>
<body>
	<h2>Test</h2>
</body>
</html>

4 .在浏览器里面输入http://localhost:8080/Servlet/one.jsp运行之后得到的结果如下所示:

网友评论