原創聲明:本文為作者原創,未經允許不得轉載,經授權轉載需注明作者和出處
上一章的demo中,我們不管是數據傳輸,業務處理還是持久化數據(操作數據庫)都是在servlet文件中完成的,這樣做,可能會顯得比較亂,因此在實際開發過程中,我們會根據不同的功能將項目分為幾個層級:
今天用分層的方式帶大家做一個實戰小項目處理用網頁的登錄權限:實現用戶登錄之后進入主頁并且顯示用戶姓名,并且一定時間內直接輸入主頁的地址還是可以訪問,超過時間了再輸入主頁地址就需要重新登錄的功能:
項目結構是這樣的:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登錄</title>
</head>
<body>
<form action="login" method="post">
<div style="color: red;">${requestScope.error }</div><!-- 獲取錯誤信息 -->
用戶名:<input type="text" name="userName" /><br />
密碼:<input type="password" name="password" /><br />
<input type="submit" value="登錄" />
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>主頁</title>
</head>
<body>
用戶編號:${sessionScope.user.id }<br /><!-- 從session中獲取用戶參數 -->
用戶名:${sessionScope.user.userName }
</body>
</html>
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//接收到的賬號密碼
String userName = req.getParameter("userName");
String password = req.getParameter("password");
LoginService loginService = new LoginService();
boolean result = loginService.login(userName,password,req, resp);
if(result){
resp.sendRedirect(req.getContextPath()+"/index.jsp");//重定向到主頁
}else{
req.setAttribute("error", "用戶名或密碼輸入錯誤");
req.getRequestDispatcher( "/login.jsp").forward(req,resp); //請求轉發到主頁
}
}
public boolean login(String userName, String password, HttpServletRequest req, HttpServletResponse resp) {
LoginDao loginDao = new LoginDao();
User user = loginDao.login(userName, password);
if(user!=null){//用戶不為空
// 手動設置session的有效期為60秒
HttpSession session = req.getSession();
String sessionId = session.getId();
Cookie cookie = new Cookie("sessionId", sessionId);
cookie.setPath(req.getContextPath());
resp.addCookie(cookie);
session.setAttribute("user", user);
session.setMaxInactiveInterval(60);
return true;
}else{
return false;
}
}
LoginDao:主要實現持久化功能(和數據庫打交道)
public class LoginDao {
// JDBC 驅動
private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
//數據庫地址 格式是 jdbc:mysql://數據庫地址(可以是ip地址):端口號(默認是3306)/數據庫名
private static final String URL = "jdbc:mysql://localhost:3306/loginDemo";
// 數據庫的用戶名與密碼,需要根據自己的設置
private static final String USER = "root";
private static final String PASS = "root";
/**
* @Title: login
* @Description: TODO(登陸)
* @param @param userName
* @param @param password
* @param @return 設定文件
* @return User 返回類型
* @throws
*/
public User login(String userName, String password) {
Connection conn = null;
Statement stmt = null;
User user = null;
try{
// 注冊 JDBC 驅動器
Class.forName(JDBC_DRIVER);
// 打開一個連接
conn = DriverManager.getConnection(URL,USER,PASS);
//拼接查詢的SQL語句
StringBuffer sql = new StringBuffer("SELECT * FROM USER WHERE userName = '");
sql.append(userName);
sql.append("' and password = '").append(password).append("'");
System.out.println(sql.toString());
// 執行 SQL 語句
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql.toString());
// 展開結果集數據
if(rs.next()){
//獲取查出來的字段
int id = rs.getInt("id");
userName = rs.getString("userName");
user = new User(id, userName);
}else{
user = null;
}
} catch(Exception se) {
// 處理 異常
se.printStackTrace();
}finally{
//關閉資源
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
return user;
}
user: 實體類(參數封裝)
public class User {
private int id;//主鍵
private String userName;//用戶名
private String password;//密碼
/**
* 構造函數
* <p>Title: </p>
* <p>Description: </p>
* @param id
* @param userName
*/
public User(int id, String userName) {
super();
this.id = id;
this.userName = userName;
}
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;
}
}
ok,以上就是本次實戰的主要代碼了,項目的邏輯:
那么當我們訪問的時候,首先輸入錯誤密碼:
輸入正確密碼:
登錄之后60(因為程序里設置的session過期時間為60秒)秒不操作或者沒有登錄的情況直接訪問主頁地址:
登錄過后60秒之內直接訪問主頁地址:
最后附上項目源碼和Sql文件:
sql文件:https://pan.baidu.com/s/1bpIkgTx
項目源碼:http://pan.baidu.com/s/1bpF3xZD