响应编码
产生原因以及解决办法:
示例:
package cn.yzu;
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 AServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
response.getWriter().println("张三");
response.getWriter().println("李四");
}
}
运行截图:
请求编码
POST请求:
GET请求(conf/server.xml):
示例:
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<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">
</head>
<body>
<form action="AServlet" method="post">
<input type="text" value="张三" name="zs">
<input type="submit" value="post请求">
</form><hr>
<form action="AServlet" method="get">
<input type="text" value="李四" name="ls">
<input type="submit" value="get请求">
</form>
</body>
</html>
AServlet
package cn.yzu;
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 AServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//处理get请求
System.out.println(request.getParameter("ls")); //不处理
String name = request.getParameter("ls");
byte[] b = name.getBytes("iso-8859-1"); //回退
name = new String(b, "utf-8"); //重编
System.out.println(name); }
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//处理post请求
request.setCharacterEncoding("utf-8");
String username = request.getParameter("zs");
System.out.println(username);
}
}
页面:
输出结果:
URL编码:
URL编码解码示例:
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import org.junit.Test;
public class Demo {
@Test
public void fun1() throws UnsupportedEncodingException {
String name = "张三";
String s = URLEncoder.encode(name, "UTF-8");//编码
System.out.println(s);
s = URLDecoder.decode(s, "utf-8"); //解码
System.out.println(s);
}
}
结果: