500 java.lang.IllegalArgumentException: Cookie值中存在无效字符[44]

500 java.lang.IllegalArgumentException: Cookie值中存在无效字符[44]_第1张图片

原因是cookie存了空格和一个英文逗号","

后面查阅资料才发现,cookie对特殊字符不支持

解决方法

对于cookie存储特殊字符,我们可以先把数据用URL编码转化,存储到cookie里,我们需要cookie的时候,再用URL解码。
需要用到两个方法
URLEncoder类的静态方法encode()
URLDecoder类的静态方法decode()

String time=",,,,,";//全是逗号
//1.先编码
time=URLDecoder.decode(time,"utf-8") 
//2.存Cookie
 response.addCookie(new Cookie("name",time));//这时候的time是编码后的
//3.如果后面获取了time,解码后再输出
time=URLDecoder.decode(time,"utf-8").
System.out.println(time);

在这里插入图片描述
下面是初学cookie用的时间代码,可以参考一下

package mycookie;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.SimpleFormatter;

@WebServlet("/CookieServlet01")
public class CookieServlet01 extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println();
        response.setContentType("text/html;charset=UTF-8");
        String msg="";
        final Cookie[] cookies = request.getCookies();
        boolean flag=true;
        if(cookies!=null){
            for(Cookie cookie:cookies){
                System.out.println(cookie.getName());
                if(cookie.getName().equals("lastTime")){
                    String value=cookie.getValue();
                    msg="欢迎回来,您上次登录的时间是"+URLDecoder.decode(value,"utf-8");
                    flag=false;
                }
            }
        }
        SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
        String time=simpleDateFormat.format(new Date());

        time=URLEncoder.encode(time,"utf-8");//编码操作
        Cookie cookie=new Cookie("lastTime",time);//把编码后的字符串存到cookie
        cookie.setMaxAge(10);
        response.addCookie(cookie);


        if(flag) msg="初次见面!!! 现在时间是!"+URLDecoder.decode(time,"utf-8");

        response.getWriter().write(msg);

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

}

你可能感兴趣的:(500)