1. 程式人生 > 其它 >登入功能實現

登入功能實現

登入功能實現

編寫前端登入頁面

1.編寫頁面程式碼login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>系統登入 - 超市訂單管理系統</title>
    <link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath }/css/style.css" />
    <script type="text/javascript">
	/* if(top.location!=self.location){
	      top.location=self.location;
	 } */
    </script>
</head>
<body class="login_bg">
    <section class="loginBox">
        <header class="loginHeader">
            <h1>超市訂單管理系統</h1>
        </header>
        <section class="loginCont">
	        <form class="loginForm" action="${pageContext.request.contextPath }/login.do"  name="actionForm" id="actionForm"  method="post" >
				<div class="info">${error }</div>
				<div class="inputbox">
                    <label for="userCode">使用者名稱:</label>
					<input type="text" class="input-text" id="userCode" name="userCode" placeholder="請輸入使用者名稱" required/>
				</div>	
				<div class="inputbox">
                    <label for="userPassword">密碼:</label>
                    <input type="password" id="userPassword" name="userPassword" placeholder="請輸入密碼" required/>
                </div>	
				<div class="subBtn">
					
                    <input type="submit" value="登入"/>
                    <input type="reset" value="重置"/>
                </div>	
			</form>
        </section>
    </section>
</body>
</html>

2.把這個登入頁面設定為首頁

如果不設定的話,預設首頁為index.jsp

<!--設定歡迎頁-->
    <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>

Dao 層

1.編寫Dao層得到使用者登入的介面

import com.xy.pojo.User;
import java.sql.Connection;

public interface UserDao {
    //從資料庫查詢指定的使用者,這裡不需要獲取連線資料庫物件,交給業務層去做
    public User getLoginUser(Connection connection, String userCode);
}

2.編寫Dao層的實現類

public class UserDaoImpl implements UserDao {
     public User getLoginUser(Connection connection, String userCode) throws SQLException {
         PreparedStatement statement = null;
         ResultSet rs = null;
         User user = null;
         if (connection != null){
             String sql = "select * from `smbms_user` where userCode=?";
             Object[] param = {userCode};
             rs = BaseDao.execute(connection, sql, param, statement, rs);
             while (rs.next()){
                 user = new User();
                 //將這些值丟給使用者
                 user.setId(rs.getInt("id"));
                 user.setUserCode(rs.getString("userCode"));
                 user.setUserName(rs.getString("userName"));
                 user.setUserPassword(rs.getString("userPassword"));
                 user.setGender(rs.getInt("gender"));
                 user.setBirthday(rs.getDate("birthday"));
                 user.setPhone(rs.getString("phone"));
                 user.setAddress(rs.getString("address"));
                 user.setUserRole(rs.getInt("userRole"));
                 user.setCreatedBy(rs.getInt("createdBy"));
                 user.setModifyBy(rs.getInt("modifyBy"));
                 user.setModifyDate(rs.getDate("modifyDate"));
             }
             BaseDao.close(null,statement,rs);
         }
         return user;
     }
}

業務層

1.編寫業務層介面

import com.xy.pojo.User;

import java.sql.SQLException;

public interface UserService {
    //使用者登入
    public User login(String userCode, String password) throws SQLException;
}

2.編寫業務層實現類

public class UserServiceImpl implements UserService{

    //業務層都會呼叫Dao層,所以我們要引入Dao層
    private UserDao userDao = null;
    public UserServiceImpl(){
        userDao = new UserDaoImpl();
    }
    public User login(String userCode, String password){
        Connection connection = null;
        User user = null;

        try {
            connection = BaseDao.getConnection();
            //通過業務層調取對應的具體的資料庫的資料
            user = userDao.getLoginUser(connection,userCode);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            BaseDao.close(connection,null,null);
        }

        return user;
    }
    @Test
    public void test(){
        UserServiceImpl userService = new UserServiceImpl();
        User admin = userService.login("admin", "1234567");
        System.out.println(admin.getUserPassword());
    }
}

Servlet

1.編寫servlet:用於獲取前端請求的引數,並呼叫業務層判斷是否存在該使用者

import com.xy.pojo.User;
import com.xy.service.user.UserService;
import com.xy.service.user.UserServiceImpl;
import com.xy.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

public class LoginServlet extends HttpServlet {
    //servlet控制層:呼叫業務層
    private UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("LoginServlet-start...");
        //獲取前端資料
        String userCode = req.getParameter("userCode");
        String userPassword = req.getParameter("userPassword");
        User user = null;
        //呼叫業務層相應的操作:和資料庫的使用者做對比

        try {
            user = userService.login(userCode,userPassword);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        if (user != null){
                //將使用者的資訊放到session中
                req.getSession().setAttribute(Constants.USER_SESSION,user);
                //跳轉到主頁
                resp.sendRedirect("jsp/frame.jsp");
            }else {
                //使用請求轉發到登入頁面,並提示使用者名稱或密碼錯誤
                req.setAttribute("error","使用者名稱或密碼不正確");
                req.getRequestDispatcher("/login.jsp").forward(req,resp);
            }
        }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

2.註冊servlet

<servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.xy.servlet.user.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login.do</url-pattern>
</servlet-mapping>