大概内容:
1.直接在目标servlet中编码参数
2.过滤器解决中文乱码
3.通过一个基类servlet解决中文乱码
直接上代码:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class Demo3Servlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//这里设置输出到前端的文本的编码方式
response.setContentType("text/html;charset=utf-8");
String name=request.getParameter("name");
String age=request.getParameter("age");
//手动将参数值编码
name=new String(name.getBytes("iso-8859-1"),"utf-8");
//控制台输出
System.out.println(name+","+age);
//网页上输出
response.getWriter().print(name+":欢迎光临");
}
//这里该方法没有实际用到
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name=request.getParameter("name");
String age=request.getParameter("age");
System.out.println(name=","+age);
response.getWriter().print(name+":欢迎光临");
}
}
1.先写一个过滤器:
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
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;
public class CharacterFilter implements Filter{
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest=(HttpServletRequest) request;
//生成我们自己包装好的类
MyRequest req=new MyRequest(httpRequest);
chain.doFilter(req, response);//放行
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("过滤器初始化了!");
}
}
/*
* 装饰类
* 解决get方式请求中的中文乱码
*/
class MyRequest extends HttpServletRequestWrapper{
public MyRequest(HttpServletRequest request) {
super(request);
}
//修改增强getParameter方法
@Override
public String getParameter(String name) {
//先获取原来参数的值
String value=super.getParameter(name);
if("get".equalsIgnoreCase(super.getMethod())){//判断是否是"get"方式请求
try {
//我们自己编码前端传来的参数
value=new String(value.getBytes("iso-8859-1"),"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
//返回我们处理过的参数值
return value;
}
//修改增强getParameterValues方法
@Override
public String[] getParameterValues(String name) {
//获取原来的参数值
String values[]=super.getParameterValues(name);
if("get".equalsIgnoreCase(super.getMethod())){//判断是否是"get"方式
for(int i=0;itry {
//我们自己编码前端传过来的参数,其中getCharacterEncoding()是我们在servlet中自己设置的编码,也可以直接写哪种编码
values[i]=new String(values[i].getBytes("ISO-8859-1"),getCharacterEncoding());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
//返回处理过的参数数组
return values;
}
////修改增强getParameterMap方法
@Override
public Map getParameterMap() {
//获取原来的参数值
Map map=super.getParameterMap();
if("get".equalsIgnoreCase(super.getMethod())){//判断是否是"get"方式
Iterator> it=map.entrySet().iterator();
while(it.hasNext()){
String values[]=it.next().getValue();
for(int i=0;itry {
values[i]=new String(values[i].getBytes("ISO-8859-1"),getCharacterEncoding());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}
//返回处理过的map
return map ;
}
}
2.写一个处理数据的servlet
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class Demo1Servlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//这里给过滤器的装饰类提前设置好编码
request.setCharacterEncoding("utf-8");
//这里设置编码是输出到前端时保证编码不出错
response.setContentType("text/html;charset=utf-8");
String name=request.getParameter("name");
String strAge=request.getParameter("age");
//输出到控制台
System.out.println(name+","+strAge);
//输出到页面
response.getWriter().print(name+":欢迎光临");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//因为这里演示get方式请求,所以直接调用doGet()方法
doGet(request, response);
}
}
1.先写一个BaseServlet类
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public abstract class BaseServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String cmd=req.getParameter("cmd");
if(null==cmd || cmd.equals("")){
cmd="execute";
}
try {
Method method=this.getClass().getMethod(cmd, HttpServletRequest.class, HttpServletResponse.class);
//声明我们自己的包装类
MyRequest myRequest=new MyRequest(req);
method.invoke(this, myRequest, resp);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
public abstract void execute(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException;
}
/*
* 装饰类
* 解决get方式请求中的中文乱码
*/
class MyRequest extends HttpServletRequestWrapper{
public MyRequest(HttpServletRequest request) {
super(request);
}
//修改增强getParameter方法
@Override
public String getParameter(String name) {
//先获取原来参数的值
String value=super.getParameter(name);
if("get".equalsIgnoreCase(super.getMethod())){//判断是否是"get"方式请求
try {
//我们自己编码前端传过来的参数,其中getCharacterEncoding()是我们在servlet中自己设置的编码,也可以直接写哪种编码
value=new String(value.getBytes("ISO-8859-1"),getCharacterEncoding());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
//返回我们处理过的参数值
return value;
}
//修改增强getParameterValues方法
@Override
public String[] getParameterValues(String name) {
//获取原来的参数值
String values[]=super.getParameterValues(name);
if("get".equalsIgnoreCase(super.getMethod())){//判断是否是"get"方式
for(int i=0;itry {
//我们自己编码前端传过来的参数
values[i]=new String(values[i].getBytes("ISO-8859-1"),getCharacterEncoding());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
//返回处理过的参数数组
return values;
}
////修改增强getParameterMap方法
@Override
public Map getParameterMap() {
//获取原来的参数值
Map map=super.getParameterMap();
if("get".equalsIgnoreCase(super.getMethod())){//判断是否是"get"方式
Iterator> it=map.entrySet().iterator();
while(it.hasNext()){
String values[]=it.next().getValue();
for(int i=0;itry {
values[i]=new String(values[i].getBytes("ISO-8859-1"),getCharacterEncoding());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}
//返回处理过的map
return map ;
}
}
2.写一个处理数据的servlet
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.hncu.utils.BaseServlet;
@SuppressWarnings("serial")
//这里要继承我们自己写的BaseServlet类,并实现他的抽象方法
public class Demo2Servlet extends BaseServlet{
@Override
//重写父类的抽象方法
public void execute(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//这里给过滤器的装饰类提前设置好
req.setCharacterEncoding("utf-8");
//这里设置编码是输出到前端时保证编码不出错
resp.setContentType("text/html;charset=utf-8");
String name=req.getParameter("name");
String age=req.getParameter("age");
System.out.println(name+","+age);
resp.getWriter().print(name+":欢迎光临!");
}
}
上述的三种方式都可以解决get方式请求的中文乱码问题,第一种最简单,第二种和第三种其实原理是差不多的:都是对HttpServletRequest进行包装,修改或者增强其中的一些方法;下面贴上主页代码和web.xml配置文件的代码:
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
<title>解决get方式请求中文乱码的两种方式演示title>
head>
<body>
<h3>过滤器解决中文乱码h3>
<a href="Demo1Servlet?name=叶秋&age=21">过滤器解决中文乱码a><br/>
<a href="Demo2Servlet?name=黄少天&age=22">基类serlvet解决中文乱码a><br/>
<a href="Demo3Servlet?name=苏沐橙&age=23">直接在servlet中解决乱码a><br/>
body>
html>
web.xml
<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">
<display-name>display-name>
<filter>
<filter-name>demo1filter-name>
<filter-class>cn.hncu.filter.CharacterFilterfilter-class>
filter>
<filter-mapping>
<filter-name>demo1filter-name>
<servlet-name>Demo1Servletservlet-name>
filter-mapping>
<servlet>
<servlet-name>Demo1Servletservlet-name>
<servlet-class>cn.hncu.servlet.Demo1Servletservlet-class>
servlet>
<servlet>
<servlet-name>Demo2Servletservlet-name>
<servlet-class>cn.hncu.servlet.Demo2Servletservlet-class>
servlet>
<servlet>
<servlet-name>Demo3Servletservlet-name>
<servlet-class>cn.hncu.servlet.Demo3Servletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>Demo1Servletservlet-name>
<url-pattern>/Demo1Servleturl-pattern>
servlet-mapping>
<servlet-mapping>
<servlet-name>Demo2Servletservlet-name>
<url-pattern>/Demo2Servleturl-pattern>
servlet-mapping>
<servlet-mapping>
<servlet-name>Demo3Servletservlet-name>
<url-pattern>/Demo3Servleturl-pattern>
servlet-mapping>
<welcome-file-list>
<welcome-file>index.jspwelcome-file>
welcome-file-list>
web-app>