首页 > 其他分享 >过滤器_编码统一处理

过滤器_编码统一处理

时间:2022-12-28 14:01:01浏览次数:32  
标签:HttpServletRequest 编码 request public 过滤器 import servlet javax 统一


问题:


处理请求数据中文问题!



     【GET/POST】



       每个servlet都要做这些操作,把公用的代码抽取-过滤器实现!



问题原因:



   出现get中文乱码,是因为在request.getParameter("参数名")方法内部没有进行提交方式判断并处理。



解决方案:



对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提交方式中文乱码

 ③当使用过滤器进行编码处理时:中文正常




 

标签:HttpServletRequest,编码,request,public,过滤器,import,servlet,javax,统一
From: https://blog.51cto.com/u_15769923/5974401

相关文章

  • go-dongle 0.2.3 版本发布,一个轻量级、语义化的 golang 编码解码、加密解密库
    dongle是一个轻量级、语义化、对开发者友好的Golang编码解码和加密解密库Dongle已被awesome-go收录,如果您觉得不错,请给个star吧github.com/golang-module/dong......
  • 布隆过滤器详解
    (1)https://blog.csdn.net/tongkongyu/article/details/124842847 (2)https://blog.csdn.net/qq_38571892/article/details/123503418......
  • 视频编码完全指南
    翻译|Alex技术审校|袁荣喜作者为KrishnaRaoVijayanagar。视频编码是一门在减少视频数据体积大小或码率的同时而不对其质量产生不良影响(在人类的视觉感知下)的科学。对......
  • 统一建模语言 (UML)
    什么是统一建模语言UML?​​UML的起源​​​​UML的历史​​​​为什么选择UML​​​​UML-概述​​UML是统一建模语言的缩写,是一种标准化建模语言,由一组集成图组成,旨......
  • 基于小波变换编码的纹理图像分割
    1.算法概述我们使用11或13维特征向量表示图像中的每个像素。两个特征用于表示像素之间的空间关系;由图像尺寸规格化的x和y像素坐标。对于灰度图像,一个特征是低通表示,它捕获......
  • 基于小波变换编码的纹理图像分割
    1.算法概述      我们使用11或13维特征向量表示图像中的每个像素。两个特征用于表示像素之间的空间关系;由图像尺寸规格化的x和y像素坐标。对于灰度图像,一个特征是低......
  • css中content可以用到的字符编码
    css中content可以用到的字符编码 项目中用到的一些特殊字符和图标html代码<divclass="cross"></div>css代码.cross{width:20px;height:20px;border-radius:10p......
  • 一个正常的人,一定是人格统一的。
    越来越体会到人际交往中一个很重要的规则,那就是,人的很多特质都是一体两面、不可分割的,当你因为一个人的某个很明显的优点而喜欢欣赏对方时,也要做好准备,对方的这个特质可能......
  • #yyds干货盘点# 名企真题专题:编码
    1.简述:描述假定一种编码的编码范围是a~y的25个字母,从1位到4位的编码,如果我们把该编码按字典序排序,形成一个数组如下:a,aa,aaa,aaaa,aaab,aaac,……,b,ba,baa,b......
  • 统一观测|如何使用 Prometheus 监控 Windows
    作者:颍川引言微软Windows是当前主流操作系统之一,在桌面和服务端均有较大市场份额。对于Linux操作系统,Prometheus可以通过NodeExporter来进行基础资源(CPU、内存......