本文为大家分享了jsp用过滤器解决request中文乱码问题,具体内容如下
(1)客户端的数据一般是通过http get/post方式提交给服务器,在服务器端用request.getparameter()
读取参数时,很容易出现中文乱码现象。
(2)用过滤器解决request中文乱码问题。
(3)代码如下:
package my;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class chinesefilter implements filter { //定义了一个过滤器 实现filter接口
private filterconfig config = null;
public void init(filterconfig config) throws servletexception {
this.config = config;
}
public void destroy() {
config = null;
}
public void dofilter(servletrequest request, servletresponse response,
filterchain chain) throws ioexception, servletexception
{
request.setcharacterencoding("gb2312");
chain.dofilter(request, response); //把过滤后的request对象转发给下一个过滤器处理
}
}
(4)部署过滤器。编辑web-infweb.xml文件,添加以下内容:
<filter>
<filter-name>cf</filter-name>
<filter-class>my.chinesefilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cf</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>request</dispatcher>
<dispatcher>forward</dispatcher>
<dispatcher>include</dispatcher>
</filter-mapping>
这里的<dispatcher></dispatcher>主要是配合requestdispatcher使用。
- 1.取值为request时 表示有请求直接来自客户端时,过滤器才能被激活,如果请求是来自requestdispatcher.forward时不激活;
- 2.取值为forward时 表示如果请求是来自requestdispatcher.forward时此过滤器才激活;
- 3.取值为include时 表示如果请求是来自requestdispatcher.include时此过滤器才激活;
- 4.取值为error时 表示如果请求是来自requestdispatcher使用“错误信息页”时此过滤器才激活;
- 5.默认为request。
(5)创建一个jsp页面检验
<%@ page contenttype="text/html; charset=gb2312" language="java" import="java.sql.*" errorpage="" %>
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head>
<body>
<%
string s=request.getparameter("data");
out.print(s);
%>
</body>
</html>
以上就是关于jsp解决request中文乱码问题的方法,希望对大家的学习有所帮助。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!