代码要求:
用户登录后,创建cookie保存用户信息
设置cookie的有效期为5分钟
在登录页循环遍历cookie数组,判断是否存在指定名称的cookie,若存在则直接跳转至欢迎页面
代码实现过程:登录页面输入用户名和密码,点击登陆后,连接数据库,并查找,如果有用户名和密码相同,则设置cookie,进入欢迎页面,并且,设置有效期5分钟的cookie,5分钟内进入登录页面直接跳转至欢迎页面!
登录页面代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'userLogin.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<% Cookie[] cookies=request.getCookies();
if(cookies!=null){
for(int i=0;i<cookies.length;i++){
if(cookies[i].getName().equals("username")){
response.sendRedirect("welcome.jsp");
}
}
}
%>
<form action="<%=request.getContextPath()%>/jsp/Login/douser.jsp" method="post" >
<div>用户名:</div> <input type="text" name="username" value=""> <div id="namediv"></div>
<div>密码:</div> <input type="password" name="password" value=""> <div id="pwddiv"></div>
<input type="submit" value="登录">
</form>
</body>
</html>
页面如图:
;
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%
request.setCharacterEncoding("UTF-8");
String username=request.getParameter("username");
String uName=URLEncoder.encode(username, "UTF-8");
String password=request.getParameter("password");
String str="欢迎光临:"+username;
session.setAttribute("mess", str);
session.setMaxInactiveInterval(15*60);
String uname=null;
String pwd=null;
UserService service=new UserServiceImpl();
List<User> list =service.selectUser(username);
for(User user:list){
uname=user.getUsername();
pwd=user.getPassword();
}
if(username.trim().equals(uname) && password.trim().equals(pwd)){
out.print(username);
Cookie nameCookie=new Cookie("username",uName.trim());
nameCookie.setMaxAge(5*60);
response.addCookie(nameCookie);
Cookie pwdCookie =new Cookie("pwd",password.trim());
pwdCookie.setMaxAge(5*60);
response.addCookie(pwdCookie);
response.sendRedirect("welcome.jsp");
}
%>
连接数据库处java代码:
BaseDao 类:
package cn.user.userdao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BaseDao {
Connection connection=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
public boolean getConnection(){
try {
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/users";
String user="root";
String password="abc12345";
connection=DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return false;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
public int executeSql(String sql,Object...params){
int updateRows=0;
if( this.getConnection()){
try {
pstmt=connection.prepareStatement(sql);
for(int i=0;i<params.length;i++){
pstmt.setObject(i+1, params[i]);
}
updateRows= pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
return updateRows;
}
public ResultSet selectsql(String sql,Object[] params){
if(this.getConnection()){
try {
pstmt=connection.prepareStatement(sql);
for(int j=0;j<params.length;j++){
pstmt.setObject(j+1, params[j]);
}
rs=pstmt.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
}
return rs;
}
public boolean closeSource(){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
if(pstmt!=null){
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
return true;
}
}
package cn.user.userdao;
import java.util.List;
import cn.user.userEntity.User;
public interface UserDao {
public boolean addInfo(User user);
public boolean selectName(String name);
public boolean selectEmail(String email);
public List<User> selectUser(String username);
}
package cn.user.userdaoImpl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import cn.user.userEntity.User;
import cn.user.userdao.BaseDao;
import cn.user.userdao.UserDao;
public class UserDaoImpl extends BaseDao implements UserDao {
public boolean addInfo(User user) {
boolean flag=false;
String sql="INSERT INTO users(id,username,PASSWORD,email,phone) VALUES (NULL,?,?,?,?)";
Object[] params={user.getUsername(),user.getPassword(),user.getEmail(),user.getPhone()};
int i= this.executeSql(sql, params);
if(i>0){
flag=true;
}
return flag;
}
public boolean selectName(String name){
boolean flag=false;
String sql="SELECT username FROM users WHERE username=?";
Object[]params={name};
ResultSet rs=this.selectsql(sql, params);
try {
if(rs.next()){
flag=true;
}
} catch (SQLException e) {
e.printStackTrace();
}
this.closeSource();
return flag;
}
public boolean selectEmail(String email) {
boolean flag=false;
String sql="SELECT email FROM users WHERE email=?";
Object[]params={email};
ResultSet rs=this.selectsql(sql, params);
try {
if(rs.next()){
flag=true;
}
} catch (SQLException e) {
e.printStackTrace();
}
this.closeSource();
return flag;
}
public List<User> selectUser(String username){
User user=null;
List<User> list=new ArrayList<User>();
String sql="SELECT username,password FROM users WHERE username=?";
Object[]params={username};
ResultSet rs=this.selectsql(sql, params);
System.out.println("1");
try {
if(rs.next()){
user=new User();
String userName=rs.getString("username");
String password=rs.getString("password");
user.setUsername(userName);
user.setPassword(password);
list.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
}
this.closeSource();
return list;
}
}
package cn.user.userService;
import java.util.List;
import cn.user.userEntity.User;
public interface UserService {
public boolean addinfo(User user);
public boolean selectName(String name);
public boolean selectEmail(String email);
public List<User> selectUser(String username);
}
package cn.user.userServiceImpl;
import java.util.List;
import cn.user.userEntity.User;
import cn.user.userService.UserService;
import cn.user.userdao.UserDao;
import cn.user.userdaoImpl.UserDaoImpl;
public class UserServiceImpl implements UserService{
private UserDao userDao;
public UserServiceImpl(){
userDao=new UserDaoImpl();
}
public boolean addinfo(User user) {
boolean flag=userDao.addInfo(user);
return flag;
}
public boolean selectName(String name) {
return userDao.selectName(name);
}
public boolean selectEmail(String email) {
return userDao.selectEmail(email);
}
public List<User> selectUser(String username){
return userDao.selectUser(username);
}
}
package cn.user.userEntity;
public class User {
private int id;
private String username;
private String password;
private String email;
private String phone;
public User(String username, String password, String email,
String phone) {
this.username = username;
this.password = password;
this.email = email;
this.phone = phone;
}
public User(int id, String username, String password, String email,
String phone) {
super();
this.id = id;
this.username = username;
this.password = password;
this.email = email;
this.phone = phone;
}
public User() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
调用数据库代码结束
欢迎页面代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'MyJsp.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script >
function exit(){
window.location="jsp/Login/userLogin.jsp";
}
</script>
</head>
<body>
<%=session.getAttribute("mess").toString() %>
<%
%>
<button type="button" onclick="exit();" >退出</button>
</body>
</html>
欢迎页面如图:
![这里写图片描述](https:
欢迎光临:张三是用session传递过来,有效时间15分钟,cookie5分钟时间过期后,点击退出,跳转到登录页面。