通过过滤器设置字符编码

来源:互联网 发布:怎样在淘宝上买到正品 编辑:程序博客网 时间:2024/05/12 11:52

一:继承filter接口


package com.filter.test;


import java.io.IOException;


import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;


/**
 * 通过过滤器设置字符编码
 * 
 * @author XXX
 * 
 */
public class FilterEncoding implements javax.servlet.Filter {


String encoding = "iso8859-1";// 默认是此编码但是实际上传递进来的是 utf-8编码


public void destroy() {


}


public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {


request.setCharacterEncoding(encoding);
chain.doFilter(request, response);
}


public void init(FilterConfig config) throws ServletException {
encoding = config.getInitParameter("encoding");
if (encoding == null) {
encoding = "iso8859-1";
}
}


}


二:web.xml 中配置 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>com.filter.test.FilterEncoding</filter-class>
<init-param>
<param-name>encoding</param-name>


<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>


</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>


三:页面中调用


<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>


<title>My JSP 'filterencoding.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>
<c:out value="${param.username}" default="none"></c:out>
<body>
<form action="filterencoding.jsp" method="post">
<input type="text" name="username" />
<input type="submit" />
</form>
</body>
</html>


0 0