做练习的时候老是出错:
The server encountered an internal error that prevented it from fulfilling this request.
源码如下:
for (int index = 0; index < cookies.length; index++) {
if(cookies[index].getName().equals("lastAccessDate")) {
lastAccessDate =cookies[index].getValue();
nowAccessDate = (nowDate.getYear() + 1900) + "年" + (nowDate.getMonth() + 1) + "月"
+ nowDate.getDate() + "日" + nowDate.getHours() + "时" + nowDate.getMinutes() + "分"
+ nowDate.getSeconds() + "秒";
oneCookie = new Cookie("lastAccessDate", nowAccessDate);
oneCookie.setMaxAge(24 * 60 * 60);
response.addCookie(oneCookie);
break;
错误发生在:response.addCookie(oneCookie);
原来是编码格式不正确,cookie不能保存中文,把上面句子中的 年 月日 时分秒 改成英文就不会报错了
若是一定要保存为中文,则把中文转化为UTF-8字符串就可以保存了:
保存的时候用java.net.URLEncoder.encode(String,”UTF-8”)编码
取回来的时候用java.net.URLDecoder.decode(String,”UTF-8”)解码
全部源码如下:
“`
<%@page import=”org.apache.naming.java.javaURLContextFactory”%>
<%@page import=”java.util.Date”%>
<%@ page pageEncoding=”UTF-8”%>
cookie
<%!String lastAccessDate = null;
String nowAccessDate = null;
Cookie oneCookie = null;
Cookie[] cookies = null;
Date nowDate = null;%>
<%
cookies = request.getCookies();
nowDate = new Date();
if (cookies == null) {
lastAccessDate = (nowDate.getYear() + 1900) + "年" + (nowDate.getMonth() + 1) + "月" + nowDate.getDate()
+ "日" + nowDate.getHours() + "时" + nowDate.getMinutes() + "分" + nowDate.getSeconds() + "秒";
lastAccessDate = java.net.URLEncoder.encode(lastAccessDate,"UTF-8"); //编码
oneCookie = new Cookie("lastAccessDate", lastAccessDate);
oneCookie.setMaxAge(24 * 60 * 60);
response.addCookie(oneCookie);
out.println("cookie:" + oneCookie.toString());
} else {
for (int index = 0; index < cookies.length; index++) {
if (cookies[index].getName().equals("lastAccessDate")) {
lastAccessDate = cookies[index].getValue();
lastAccessDate = java.net.URLDecoder.decode(lastAccessDate,"UTF-8"); //解码
nowAccessDate = (nowDate.getYear() + 1900) + "年" + (nowDate.getMonth() + 1) + "月"
+ nowDate.getDate() + "日" + nowDate.getHours() + "时" + nowDate.getMinutes() + "分"
nowAccessDate = java.net.URLEncoder.encode(nowAccessDate,"UTF-8"); //编码
oneCookie = new Cookie("lastAccessDate", nowAccessDate);
oneCookie.setMaxAge(24 * 60 * 60);
response.addCookie(oneCookie);
break;
}
}
}
out.print("您上次访问本系统的时间是在:" + lastAccessDate);
%>