网上图书商城项目学习笔记-037工具类之BaseServlet及统一中文编码
1.统一中文编码分析
tomcat默认esetISO-8859-1编码,在servlet中,可能通过request的setCharacterEncoding(charset)和response.setContentType("text/html;charset=UTF-8");处理post请求编码,但get请求的编码控制不了,所以,如果请求类型是get,则用装饰者模式把request整个调包
2.EncodingFilter.java
package cn.itcast.filter; 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;
import javax.servlet.http.HttpServletRequest; public class EncodingFilter implements Filter {
private String charset = "UTF-8";
@Override
public void destroy() {} @Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
if(req.getMethod().equalsIgnoreCase("GET")) {
if(!(req instanceof GetRequest)) {
req = new GetRequest(req, charset);//处理get请求编码
}
} else {
req.setCharacterEncoding(charset);//处理post请求编码
}
chain.doFilter(req, response);
} @Override
public void init(FilterConfig fConfig) throws ServletException {
String charset = fConfig.getInitParameter("charset");
if(charset != null && !charset.isEmpty()) {
this.charset = charset;
}
}
}
3.GetRequest.java 装饰者模式
package cn.itcast.filter; import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper; /**
* 对GET请求参数加以处理!
* @author qdmmy6
*
*/
public class GetRequest extends HttpServletRequestWrapper {
private HttpServletRequest request;
private String charset; public GetRequest(HttpServletRequest request, String charset) {
super(request);
this.request = request;
this.charset = charset;
} @Override
public String getParameter(String name) {
// 获取参数
String value = request.getParameter(name);
if(value == null) return null;//如果为null,直接返回null
try {
// 对参数进行编码处理后返回
return new String(value.getBytes("ISO-8859-1"), charset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
} @SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public Map getParameterMap() {
Map<String,String[]> map = request.getParameterMap();
if(map == null) return map;
// 遍历map,对每个值进行编码处理
for(String key : map.keySet()) {
String[] values = map.get(key);
for(int i = 0; i < values.length; i++) {
try {
values[i] = new String(values[i].getBytes("ISO-8859-1"), charset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
// 处理后返回
return map;
} @Override
public String[] getParameterValues(String name) {
String[] values = super.getParameterValues(name);
for(int i = 0; i < values.length; i++) {
try {
values[i] = new String(values[i].getBytes("ISO-8859-1"), charset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
return values;
}
}
3.BaseServlet.java
package cn.itcast.servlet; import java.io.IOException;
import java.lang.reflect.Method; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* BaseServlet用来作为其它Servlet的父类
*
* @author qdmmy6
*
* 一个类多个请求处理方法,每个请求处理方法的原型与service相同! 原型 = 返回值类型 + 方法名称 + 参数列表
*/
@SuppressWarnings("serial")
public class BaseServlet extends HttpServlet {
@Override
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");//处理响应编码 /**
* 1. 获取method参数,它是用户想调用的方法 2. 把方法名称变成Method类的实例对象 3. 通过invoke()来调用这个方法
*/
String methodName = request.getParameter("method");
Method method = null;
/**
* 2. 通过方法名称获取Method对象
*/
try {
method = this.getClass().getMethod(methodName,
HttpServletRequest.class, HttpServletResponse.class);
} catch (Exception e) {
throw new RuntimeException("您要调用的方法:" + methodName + "它不存在!", e);
} /**
* 3. 通过method对象来调用它
*/
try {
String result = (String)method.invoke(this, request, response);
if(result != null && !result.trim().isEmpty()) {//如果请求处理方法返回不为空
int index = result.indexOf(":");//获取第一个冒号的位置
if(index == -1) {//如果没有冒号,使用转发
request.getRequestDispatcher(result).forward(request, response);
} else {//如果存在冒号
String start = result.substring(0, index);//分割出前缀
String path = result.substring(index + 1);//分割出路径
if(start.equals("f")) {//前缀为f表示转发
request.getRequestDispatcher(path).forward(request, response);
} else if(start.equals("r")) {//前缀为r表示重定向
response.sendRedirect(request.getContextPath() + path);
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
网上图书商城项目学习笔记-037工具类之BaseServlet及统一中文编码的更多相关文章
- 网上图书商城项目学习笔记-036工具类之CommonUtils及日期转换器
1.CommonUtils.java package cn.itcast.commons; import java.util.Map; import java.util.UUID; import or ...
- 网上图书商城项目学习笔记-035工具类之JdbcUtils及TxQueryRunner及C3P0配置
事务就是保证多个操作在同一个connection,TxQueryRunner通过JdbcUtils获取连接,而JdbcUtils通过ThreadLocal<Connection>确保了不同 ...
- 网上图书商城项目学习笔记-011Book模块查询(分页)
一.流程分析 1.图书模块 2.分布分析 二.代码 1.view层 1)list.jsp <%@ page language="java" import="java ...
- 网上图书商城项目学习笔记-012BOOK模块查询2
一.分析 > 按图名查询(模糊)(分页)> 按作者查询(分页)> 按出版社查询(分页)> 按id查询> 多条件组合查询(分页) 二.代码 1.view层 (1)gj.js ...
- 网上图书商城项目学习笔记-014购物车模块页面javascrip
一.流程分析 二.代码 1.view层 (1)list.jsp <%@ page language="java" import="java.util.*" ...
- Google Guava学习笔记——基础工具类Joiner的使用
Guava 中有一些基础的工具类,如下所列: 1,Joiner 类:根据给定的分隔符把字符串连接到一起.MapJoiner 执行相同的操作,但是针对 Map 的 key 和 value. 2,Spli ...
- 【Java EE 学习 25 上】【网上图书商城项目实战】
一.概述 1.使用的jdk版本:1.6 2.java EE版本:1.6 3.指导老师:传智播客 王建 二.小项目已经实现的功能 普通用户: 1.登陆 2.注册 3.购物 4.浏览 管理员用户(全部管理 ...
- Google Guava学习笔记——基础工具类针对Object类的使用
Guava 提供了一系列针对Object操作的方法. 1. toString方法 为了方便调试重写toString()方法是很有必要的,但写起来比较无聊,不管如何,Objects类提供了toStrin ...
- Google Guava学习笔记——基础工具类Preconditions类的使用
Preconditions类是一组静态方法用来验证我们代码的状态.Preconditons类很重要,它能保证我们的代码按照我们期望的执行,如果不是我们期望的,我们会立即得到反馈是哪里出来问题,现在我们 ...
随机推荐
- android xml的生成与解析
Main java package com.itheima.xml; import android.app.Activity; import android.content.Context; impo ...
- SecureCRT for Linux突破30天使用限制
当然还有一种方法,就是当你试用点i agree到时候,在~/.vandyke/Config 会生成一个文件SecureCRT_eval.lic,删除以后就可以恢复30天试用
- Linux 配置
零:个性化 主题:Radiance 主题颜色: gtk-color-scheme = "base_color:#CCE8CF\nfg_color:#006400\ntooltip_fg_co ...
- json-lib-2.4.jar Bug,json字符串中value为"[value]"结构时,解析为数组,不会解析成字符串
使用json-lib.jar 2.4进行json字符串转换为对象时发现一个bug.贴下测试代码: <dependency> <groupId>net.sf.json-lib&l ...
- linux与windows共享剪贴板(clipboard)
linux与windows共享剪贴板(clipboard)的方法 先说两句废话,其实linux和windows之间不需要共享剪贴板,直接在putty中,按住SHIFT+鼠标选择就可以了. 但是作为一种 ...
- mysql table readonly
if the table does not have primary key or unique non-nullable defined, then MySql workbench could no ...
- 利用ApnsPHP包向IOS推送消息
header('content-type:text/html;charset=utf-8'); require_once 'ApnsPHP/Autoload.php'; require_once 'A ...
- python学习之jquery小练习
<html> <head> <title>html/css/js学习小结</title> <script src="jquery-1.8 ...
- svn团队环境
1.安装VisualSVN Server VisualSVN-Server-3.3.1-x64.msi 下载,并安装标准版(免费) 2.下载TortoiseSVN TortoiseSVN-1.8.11 ...
- Java学习之路:1、HelloWorld
似乎每种语言都是从HelloWorld开始的,所以,我的第一个java程序,也应该是这样开始的! 1.配置好jdk后,开始编写HelloWorld.java package second;//这个应该 ...