问题:
几乎每一个Servlet都要涉及编码处理:
处理请求数据中文问题!
【GET/POST】
每个servlet都要做这些操作,把公用的代码抽取-过滤器实现!
问题原因:
出现get中文乱码,是因为在request.getParameter("参数名")方法内部没有进行提交方式判断并处理。
解决方案:
1.对指定接口的某一个方法进行功能扩展,可以使用代理:
对request对象(目标对象),创建代理对象
2.对
HttpServletRequestWrapper类中的getParameter方法进行重写
代码实现思路:
1.index.jsp 登陆,输入“中文”
2.LoginServlet.java 直接处理登陆请求
3.EncodingFilter.java 过滤器处理请求数据编码:GET/POST
代码实现:
编码处理的过滤器一:
package com.cn.filter;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 编码处理过滤器
* @author liuzhiyong
*
*/
public class EncodingFilter implements Filter{
/**
* 过滤器业务处理方法:处理公用的业务逻辑操作
*/
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
//转型
final HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
/**
* 1.处理公用的逻辑业务
*/
//设置post方式提交的请求的编码
request.setCharacterEncoding("utf-8");//只对POST提交有效
//设置页面打开时的编码格式,设置响应体的编码格式
response.setContentType("text/html;charset=utf-8");
/**
* 出现get中文乱码,是因为在request.getParameter("参数名")方法内部没有进行提交方式判断并处理
*
* 解决:对指定接口的某一个方法进行功能扩展,可以使用代理:
* 对request对象(目标对象),创建代理对象
*/
HttpServletRequest requestProxy =(HttpServletRequest)Proxy.newProxyInstance(
request.getClass().getClassLoader(),// 定义代理对象类的类加载器。负责加载类的对象
new Class[]{HttpServletRequest.class}, //代理类要实现的接口列表
new InvocationHandler(){ 当调用目标对象对象方法的时候, 自动触发事务处理器
@Override
public Object invoke(Object proxy, Method method, Object[] args)//这里的args是调用方法传入的参数
throws Throwable {
//定义方法返回值
Object returnValue = null;
//当前执行方法的方法名
String methodName = method.getName();
//判断:对getParameter方法进行GET方式提交中文处理
if("getParameter".equals(methodName)){
//获取请求数据的值
String parameterValue = request.getParameter(args[0].toString());//调用目标对象的方法
//获取提交请求的提交方式
String submitMethod = request.getMethod();
//判断,如果是GET提交,需要对数据进行处理(POST提交已经处理过了)
if("GET".equals(submitMethod)){//注意在Servlet中这里是大写的GET
if(parameterValue!=null && !"".equals(parameterValue.trim())){
//处理GET方式提交的中文
parameterValue = new String(parameterValue.getBytes("ISO-8859-1"), "UTF-8");
}
}
return parameterValue;//返回getParameter方法的返回值
}else{
returnValue = method.invoke(request, args);//调用目标对象request的其它方法
return returnValue;//返回返回值
}
}
});
//2.放行(进入下一个过滤器或者进入Servlet)
chain.doFilter(requestProxy, response);//传入request代理对象requestProxy
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
编码处理的过滤器二:
package com.cn.filter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
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.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
public class EncodingFilter implements Filter{
//保存filterConfig
private FilterConfig filterConfig;
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
//类型转换
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
//得到配置文件中的编码格式:
String encoding = filterConfig.getInitParameter("encoding");
if(encoding == null){
encoding = "utf-8";
}
//对POST方式提交的请求进行编码
request.setCharacterEncoding(encoding);
//设置页面打开时的响应体的编码格式
response.setContentType("text/html;charset="+encoding);
MyHttpServletRequest mRequest = new MyHttpServletRequest(request);
//如果是GET请求方式
chain.doFilter(mRequest, response);//放行
}
public void destroy() {
}
}
class MyHttpServletRequest extends HttpServletRequestWrapper{
public MyHttpServletRequest(HttpServletRequest request) {
super(request);
}
@Override
public String getParameter(String name) {
//拿到原来的值
String parameterValue = super.getParameter(name);
//如果传入的值为空
if(parameterValue == null){
return null;
}
//判断请求方式
String method = super.getMethod();
if("get".equalsIgnoreCase(method)){//如果是get方式提交的请求
try {
parameterValue = new String(parameterValue.getBytes("iso-8859-1"), super.getCharacterEncoding());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return parameterValue;
}
}
登录的Servlet
package com.cn.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取参数
String userName = request.getParameter("userName");
System.out.println(request.getMethod() + "方式提交的用户名:" + userName);
}
}
web.xml中过滤器配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
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_3_0.xsd">
<!-- 编码处理过滤器配置 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>com.cn.filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.cn.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
输入页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.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>
<body>
<form name="formLogin1" action="${pageContext.request.contextPath }/login" method="post">
用户名:<input type="text" name="userName"/><br/>
<input type="submit" value="POST提交"/>
</form>
<form name="formLogin2" action="${pageContext.request.contextPath }/login" method="get">
用户名:<input type="text" name="userName"/><br/>
<input type="submit" value="GET提交"/>
</form>
</body>
</html>
①当代码中不进行任何的编码处理时:中文乱码
②当设置post方式提交的请求的编码时,只对POST提交有效:GET提交方式中文乱码
③当使用过滤器进行编码处理时:中文正常