实验:
不同用户访问服务器,他们的网页背景色不一样。好象记住了不同用户的选择。这个如何实现?
思路:关于背景色的值应该保存到cookie里面
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'");
out.println("<html>");
out.println("<head>");
out.println("<meta content='text/html; charset=UTF-8' http-equiv='content-type'>");
out.println("<title>背景颜色</title>");
out.println("</head>");
out.println("<body>");
out.println("<form action=\"login.do\" method=\"post\">");
out.println("<input type=\"radio\" name=\"bgcolor\" value=\"red\"/>红色<br/>");
out.println("<input type=\"radio\" name=\"bgcolor\" value=\"blue\"/>蓝色<br/> ");
out.println("<input type=\"radio\" name=\"bgcolor\" value=\"green\"/>绿色<br/>");
out.println("<input type=\"submit\" value=\"发送\">");
out.println("</form>");
String colors = request.getParameter("bgcolor");//获取html中的颜色
if(colors!=null) {
Cookie cookie = new Cookie("name",colors);//创建cookie对象
response.addCookie(cookie);//把cookie添加进去
}
Cookie[] cookies = request.getCookies();//创建cookies数组存放三个颜色
if(cookies!=null) {
for(int i=0;i<cookies.length;i++) {
if(cookies[i].getName().equals("name")) {//获取浏览器选中的cookie
colors = cookies[i].getValue();//获取颜色值
}
}
//out.println(colors);
out.println("<body bgcolor=\""+ colors +"\">");//修改背景色
out.println("</body>");
out.println("</html>");
out.close();
}
}