//下面是监听器代码
public class LoginListener implements HttpSessionListener {
private static int count;
public static int get(){
return count;
}
public LoginListener() {
// TODO Auto-generated constructor stub
}
public void sessionCreated(HttpSessionEvent arg0) {
count++;
}
public void sessionDestroyed(HttpSessionEvent arg0) {
count--;
}
}
//这个是首页登录的html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="../DoLogin.do">
用户名:<input type="text" name="name"><br>
密码:<input type="password" name="passwd"><br>
<input type="submit" name="sub" value="提交">
</form>
</body>
</html>
//这个是提交的action
public class DoLogin extends HttpServlet {
private Map<String,String> map;
public DoLogin() {
map=new HashMap<String,String>();
map.put("xiao", "1");
map.put("xiao1", "12");
map.put("xiaozhu", "123");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
String passwd = request.getParameter("passwd");
if(map.containsKey(name)&&map.get(name).equals(passwd)){
request.getSession().setAttribute("user", name);
request.getRequestDispatcher("/success.view").forward(request, response);
}
else{
response.sendRedirect("LoginListener/index");
}
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
//这个是登录成功之后转到的界面
public class LoginSuccess extends HttpServlet {
/**
* Constructor of the object.
*/
public LoginSuccess() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void success(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
response.setContentType("text/html;charset=utf-8");
String user = (String) request.getSession().getAttribute("user");
PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>显示用户登录次数</TITLE></HEAD>");
out.println(" <BODY>");
out.println("用户名:"+user+"");
out.println("登录次数"+LoginListener.get());
out.println(" </BODY>");
out.println("</HTML>");