JSP使用过滤器解决request getParameter中文乱码问题方法学习--jsp

   在服务器端用request.getParameter()读取参数时,很容易出现中文乱码现象,下面是JSP用过滤器解决request中文乱码问题的具体实现

(1)客户端的数据一般是通过HTTP GET/POST方式提交给服务器,在服务器端用request.getParameter()读取参数时,很容易出现中文乱码现象。

(2)用过滤器解决request中文乱码问题。

(3)代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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-INF\web.xml文件,添加以下内容:

?
1
2
3
4
5
6
7
8
9
10
11
<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页面检验

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<%@ 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>


更多Java知识学习请访问Java免费学习   Java自学网 http://www.javalearns.com

关注微信号:javalearns  ,随时随地学Java

今天看到一个手机也能赚钱的网站,与大家分享(真实可信,已亲身体验):

http://javalearns.jifenqiang.com/

?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值