- package info.dyndns.oszc;
- import java.io.IOException;
- import java.io.OutputStream;
- import java.io.PrintWriter;
- import java.util.Date;
- import javax.servlet.ServletException;
- import javax.servlet.http.Cookie;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class CookieDemo1 extends HttpServlet {
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- Cookie[] cookies = request.getCookies();
- boolean visited = false;
- response.setContentType("text/html;charset=UTF-8"); //设置头文件编码是UTF-8,浏览器用utf-8解码
- OutputStream out = response.getOutputStream(); //response.getOutputStream()默认编码是gb2312
- for (int i=0; cookies !=null && i<cookies.length ; i++)
- {
- if (cookies[i].getName().equals("lastVisit"))
- {
- visited = true;
- out.write("您上次访问的时间为:".getBytes());
- //用gb2312写入,显然会出现乱码,所以要修改为out.write("您上次访问的时间为:".getBytes("UTF-8"));
- String lastVisit =cookies[i].getValue();
- Date date =new Date( Long.parseLong(lastVisit) );
- out.write(date.toLocaleString().getBytes());
- }
- }
- if (!visited)
- {
- out.write("第一次访问本网站!".getBytes());//也会出现乱码,修改方法如上
- }
- Cookie cookie = new Cookie("lastVisit", System.currentTimeMillis()+"");
- cookie.setMaxAge(1*60*60); //持续一个小时
- cookie.setPath("/day07");
- response.addCookie(cookie);
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- }
- }
Servlet中response.getOutputStream() 默认编码是gb2312
最新推荐文章于 2023-12-15 16:25:53 发布