写了一个cookie的定义和获取,结果我输入中文后,页面报错
报错信息如下:
type Exception reportmessage An exception occurred processing JSP page /demo1/page3.jsp at line 16description The server encountered an internal error that prevented it from fulfilling this request.exception org.apache.jasper.JasperException: An exception occurred processing JSP page /demo1/page3.jsp at line 1613: 14: <%15: Cookie cookie=new Cookie("message","涓枃");16: response.addCookie(cookie);17: %>18: 19: Stacktrace: org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:575) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:477) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339) javax.servlet.http.HttpServlet.service(HttpServlet.java:731)root cause java.lang.IllegalArgumentException: Control character in cookie value or attribute. org.apache.tomcat.util.http.CookieSupport.isHttpSeparator(CookieSupport.java:205) org.apache.tomcat.util.http.CookieSupport.isHttpToken(CookieSupport.java:229) org.apache.tomcat.util.http.ServerCookie.appendCookieValue(ServerCookie.java:185) org.apache.catalina.connector.Response.generateCookieString(Response.java:1054) org.apache.catalina.connector.Response.addCookie(Response.java:996) org.apache.catalina.connector.ResponseFacade.addCookie(ResponseFacade.java:380) org.apache.jsp.demo1.page3_jsp._jspService(page3_jsp.java:97) org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) javax.servlet.http.HttpServlet.service(HttpServlet.java:731) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:439) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339) javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
解决方案:cookie也要转码的
定义一个cookie:
1 <%@page import="java.net.URLEncoder"%> 2 <%@ page language="java" contentType="text/html; charset=UTF-8" 3 pageEncoding="UTF-8"%> 4 5 6 7 815 <%16 //转码17 Cookie cookie=new Cookie("message",URLEncoder.encode("中文", "utf-8"));18 response.addCookie(cookie);19 %>20 21page3 9 10 11
page4.jsp(获取cookie)
1 <%@page import="java.net.URLDecoder"%> 2 <%@page import="java.net.URLEncoder"%> 3 <%@ page language="java" contentType="text/html; charset=UTF-8" 4 pageEncoding="UTF-8"%> 5 6 7 8 9page4 10 11 12 <%13 String text = request.getParameter("text");14 out.print("text------------->"+text);15 Cookie[] cookies=request.getCookies();16 if(cookies!=null){17 for(Cookie cookie:cookies){18 if(cookie.getName().equals("message")){19 //cookie解码20 out.print("cookie value------>"+URLDecoder.decode(cookie.getValue(), "utf-8"));21 }22 }23 %>24 25 26