当form表单提交的是汉语时,将信息储存到cookie中会出现乱码问题。
解决cookie不支持中文核心代码:
URLEncoder.encode("content","code");
//将内容按照指定的编码方式做URI编码处理
URLDecoder.decoder(cookie.getName(),"code");
案例:
<%@page import="java.net.URLDecoder"%>
<%@page import="java.io.PrintWriter"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
Cookie[] cookies=request.getCookies();
//ArrayList<String> list=new ArrayList<String>();
String name="";//如果不用String过渡,后期输出jsp会出现json数据的输出
PrintWriter ot=response.getWriter();
for(int i=0;i<cookies.length;i++){
name=URLDecoder.decode(cookies[i].getValue(),"utf-8");
ot.print(name);
}
%>
</body>
</html>
package com.cookie_session;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/LoginServlet")
@MultipartConfig
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
PrintWriter out=response.getWriter();
String user=request.getParameter("user");
String pwd=request.getParameter("pwd");
Cookie cookie=new Cookie("user",URLEncoder.encode(user,"utf-8"));
response.addCookie(cookie);
response.sendRedirect("/test05/begin.jsp");
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="LoginServlet" method="post" enctype="multipart/form-data">
账号:<input type="text" name="user"><br/>
密码:<input type="password" name="pwd"><br/>
文件:<input type="file" name="file_name">
<input type="submit" value="提交">
</form>
</body>
</html>