jsp实现登录,并用数据库存储,并记录登录的次数以及登录的账号,同一个账号只记录一次,重复进入也只记一次。
登录页面:login.jsp
<%!
String name="";
String password="";
String mess=null;
%>
<%
Cookie[] cookies=request.getCookies();
for(Cookie cookie:cookies){
if(cookie.getName().equals("name")){
name=cookie.getValue();
}
if(cookie.getName().equals("password"))
{
password=cookie.getValue();
}
}
%>
<form action="vefity.jsp" method="post">
用户名:<input name="name" value="<%=name==null?"":name %>"/><br/>
密码:<input type="password" name="password" value="<%=password==null?"":password%>"/><br/>
<input type="submit" value="登录"/>
<%
mess=(String)request.getAttribute("mess");
if(mess!=null){
out.print(mess);
}
%>
</form>
验证页面:vefity.jsp
<%
out.print("登录成功");
String name=request.getParameter("name");
String password=request.getParameter("password");
try{
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
//编译sql
String sql="select * from login where name=? and password=?";
PreparedStatement pst=connection.prepareStatement(sql);
//设置参数
pst.setObject(1, name);
pst.setObject(2, password);
//执行sql
ResultSet resultSet=pst.executeQuery(); //查询出满足的数据
if(resultSet.next()){
Cookie cookie1=new Cookie("name",name);
Cookie cookie2=new Cookie("password",password);
response.addCookie(cookie1);
response.addCookie(cookie2);
response.sendRedirect("success.jsp?name="+name);
//强转可以判断空值
Integer count=(Integer)application.getAttribute("count");
List<String> ids=(List)application.getAttribute("id"); //创建一个集合,存放获取属性名为id的元素
if(ids==null){
application.setAttribute("count", 1);
List id=new ArrayList(); //创建一个集合
id.add(name); //添加一个元素放到集合中
application.setAttribute("id", id); //将集合中的元素,放在属性名为id的属性中
}
else{
boolean flag=false;
for(String s:ids){
if(s.equals(name)){
flag=true;
break;
}
}
if(!flag){
ids.add(name);
application.setAttribute("count", ++count);
}
}
}
else{
request.setAttribute("mess", "账号或密码错误");
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}catch(Exception e){
System.out.print("错误");
}
%>
登录成功的页面success.jsp
登录成功,用户名是:
<%=request.getParameter("name")
%>
当前访问人数:<%=application.getAttribute("count")
%>
访问的名称<%
List<String> ids=(List)application.getAttribute("id");
for(String id:ids){
out.print(id);
}
%>