serlvet session and cookie
实验
1.以图片方式,向页面输出红色的当前时间日期,格式为“yyyy年MM月dd日 HH:mm:ss”。
2.又一个简单的登录功能(一定时期的免登陆):
(1)登录界面输入用户名、密码,勾选“一个星期自动登录”后,提交至CheckServlet;
(2)CheckServlet中判断用户名密码非空且内容相同,为登录成功,将用户名放入Session,并将用户名保存在Cookie中;设置Cookie有效时长为15分钟(模拟1个星期)。登录成功后转至首页(IndexServlet),在其中显示“欢迎您”+用户名。
(3)IndexServlet提取Cookie信息,如果已保存有用户名(即已登录)直接显示“欢迎您”+用户名,并将用户名放入Session,否则提供登录页面的链接。
(4)“退出登录”:删除Session的登录状态、删除已保存的Cookie。
第一题:
package ch04;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.*;
public class LastsAccessServlet extends HttpServlet{
private static int WIDTH = 300;
private static int HEIGHT = 40;
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
response.setContentType("text/html;charset=UTF-8");
HttpSession session = request.getSession();
response.setContentType("image/jpeg");
ServletOutputStream sos = response.getOutputStream();
String nowtime = null; //日期格式
Date date=new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日_HH:mm:ss");
String currentTime = simpleDateFormat.format(new Date());
Cookie cookie = new Cookie("nowtime", currentTime); //传入键和值
response.addCookie(cookie); //传入cookie对象
Cookie[] cookies = request.getCookies(); //获取cookies对象
BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_BGR); //创建内存图像
Graphics g = image.getGraphics(); //调用画笔
for(int i = 0;cookies != null && i<cookies.length;i++) {
if("nowtime".equals(cookies[i].getName())) {
nowtime = cookies[i].getValue();
break;
}
}
drawRands(g,nowtime); //使用画笔画图
g.dispose(); //关闭画笔
ByteArrayOutputStream bos = new ByteArrayOutputStream(); //将图像写入到客户端
ImageIO.write(image, "JPEG", bos);
byte [] buf = bos.toByteArray();
response.setContentLength(buf.length);
sos.write(buf);
bos.close();
sos.close();
}
//drawRands方法
private void drawRands(Graphics g, String nowtime) {
g.setColor(Color.RED);
g.setFont(new Font(null,Font.ITALIC|Font.BOLD,18));
g.drawString(nowtime, 16, 30);
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
this.doGet(request,response);
}
}
第二题:
login.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html"; charset=UTF-8>
<title>
Insert titile here
</title>
</head>
<body>
<form action="CheckServlet" method="post" >
用户名:<input type="text" name="username" /><br>
密 码:<input type="password" name="password" /><br>
<input type="checkbox" name="time" value="YES">7天内有效<br>
<input type="submit" value="登录" />
</form>
</div>
</body>
</html>
User 类:
package ch05;
public class User { //用户对象
private String username;
private String password;
private String time;
public String getUsername() {
return username;
}
public void setUsername(String username) { //用户对象写入方法
this.username = username;
}
public String getPassword() { //用户对象获取方法
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
CheckServlet 类:
package ch05;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class CheckServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter(); //输出流
String username = (String) request.getParameter("username"); //从html文件中获取用户名密码,cookie时间
String password = (String) request.getParameter("password");
String time = (String) request.getParameter("time");
if(username.equals(password) && !username.equals("") && !password.equals("")){ //判断用户密码非空和一样
User user = new User(); //构造用户对象的方法
user.setUsername(username); //写入用户对象方法
user.setPassword(password);
user.setTime(time);
request.getSession().setAttribute("user", user); //将用户名保存在session中
request.getSession().setAttribute("time", user); //将时间保存在session中
response.sendRedirect("IndexServlet"); //转到登陆页面
}else {
out.print("密码用户名错误或为空");
}
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
doGet(request,response);
}
}
IndexServlet 类:
package ch05;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class IndexServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter(); //输出流
HttpSession session = request.getSession(); //使用session对象
User user = (User) session.getAttribute("user"); //从session中读取用户和时间
User time = (User) session.getAttribute("time");
if(user == null) { //登陆为空时
out.print("您还没有登陆,请前往前方网址登陆:+<a href='login.html'>网址</a>");
}else{
out.print("欢迎您:"+user.getUsername()+"<br>");
out.print("<a href='LogoutServlet'>退出</a>");
}
if("YES".equals(time.getTime())) {
out.print("欢迎您再次登陆");
Cookie cookie = new Cookie("JSESSIONID",session.getId()); //将sessionID写入到cookie中
cookie.setMaxAge(15*60); //cookie保存周期
cookie.setPath("qzh"); //cookie存储路径
response.addCookie(cookie); //将cookie信息写入到浏览器中
}
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
doGet(request,response);
}
}