jsp:include使用方法及中文参数乱码的解决

下面的例子是1.jsp包含index.jsp,并向index.jsp传递参数,index.jsp接收参数并显示.
1.jsp:


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP '1.jsp' starting page</title>
</head>

<body>
	<jsp:include page="index.jsp">
		<jsp:param value="我是中文" name="param" />
	</jsp:include>
</body>
</html>

index.jsp接收参数:


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String param=request.getParameter("param");
	out.println(param);
 %>

运行时发现,即使两个文件的Encoding都是UTF-8,中文还是显示乱码。解决方法:增加一个过滤器,把ServletRequest的编码转换成UTF-8.
新建一个类EncodeFilter,实现javax.servlet.Filter接口:


package pocketdigi;

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;

public class EncodeFilter implements Filter {
	private FilterConfig filterConfig;
	private String encode;
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		filterConfig=null;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding(encode);
		//设置编码
		filterChain.doFilter(request, response);
		//调用FilterChain中的下一个过滤器,如果这是最后一个过滤器,调用请求的资源
		//过滤器是在传送参数之后,被接收到之前调用的
		
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		this.filterConfig = filterConfig;
		encode=filterConfig.getInitParameter("Encode");
		//读取web.xml中配置的参数
	}

}

在web.xml中还需要配置过滤器:


  <filter>
  	<filter-name>EncodeFilter</filter-name>
  	<filter-class>pocketdigi.EncodeFilter</filter-class>
  	<init-param>
  		<param-name>Encode</param-name>
  		<param-value>UTF-8</param-value>
  		<!-- 设置参数,在过滤器中读取 -->
  	</init-param>
  </filter>
  <filter-mapping>
  		<filter-name>EncodeFilter</filter-name>
  		<url-pattern>/*</url-pattern>
  		<!-- /是相对该项目而言,并非站点根目录,这里过滤该对项目所有jsp和servlet请求 -->
  </filter-mapping>

© 2012, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记