JavaWeb小工程實戰演練(二)

登錄功能

1. 網頁設計

同樣我還是在模板之家下載了這樣一個登錄界面,自己就不設計頁面了 o(* ̄▽ ̄*)o

在這裏插入圖片描述

2.後臺代碼設計

登錄servlet:LoginServlet

package cn.hehewocao.Servlet;

import cn.hehewocao.Dao.AdminDao;
import cn.hehewocao.POJO.Admin;
import cn.hehewocao.Service.AdminService;
import cn.hehewocao.Service.AdminServiceImp;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        Admin admin = new Admin();
        Map<String, String[]> parameterMap = req.getParameterMap();
        try {
            BeanUtils.populate(admin,parameterMap);//BeanUtils封裝Admin對象
            AdminService as = new AdminServiceImp();
            admin = as.login(admin);//查找數據庫
            if(admin!=null) {
                HttpSession session = req.getSession();
                session.setAttribute("admin", admin);//將改admin存入session
                resp.sendRedirect(req.getContextPath()+"/findServletByPage");//重定向到FindServletByPage開始查詢用戶信息
            }else {
                req.setAttribute("login_msg","用戶名或密碼錯誤!");//保存登錄信息用以回顯
                req.getRequestDispatcher("/index.jsp").forward(req,resp);
            }

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }
}

AdminServiceImp()類:

package cn.hehewocao.Service;

import cn.hehewocao.Dao.AdminDao;
import cn.hehewocao.Dao.AdminDaoImp;
import cn.hehewocao.POJO.Admin;

/**
 *  管理員接口的實現類
 */

public class AdminServiceImp implements AdminService {
    @Override
    public Admin login(Admin admin) {
        return new AdminDaoImp().find(admin.getAdministrators(),admin.getPassword());
    }
}

AdminDaoImpl類:

package cn.hehewocao.Dao;

import cn.hehewocao.POJO.Admin;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import cn.hehewocao.JDBC.DBCPUtils;
import javax.sql.DataSource;
import java.sql.SQLException;

/**
 *  管理員數據訪問層的實現類
 */
public class AdminDaoImp implements AdminDao {
    @Override
    public Admin find(String administrator,String password) {
        String sql = "select * from admin where administrator = ? and password = ?";
        QueryRunner qr = new QueryRunner((DataSource) DBCPUtils.getDateSource());
        Admin admin = new Admin();
        try {
           admin = qr.query(sql, new BeanHandler<Admin>(Admin.class), administrator,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return admin;
    }
}

3. JSP頁面設計

JSP界面主要用於錯誤信息的回顯。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
    <title>管理員登錄</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script type="application/x-javascript"> addEventListener("load", function () {
        setTimeout(hideURLbar, 0);
    }, false);

    function hideURLbar() {
        window.scrollTo(0, 1);
    } </script>
    <meta name="keywords"
          content="Flat Dark Web Login Form Responsive Templates, Iphone Widget Template, Smartphone login forms,Login form, Widget Template, Responsive Templates, a Ipad 404 Templates, Flat Responsive Templates"/>
    <link href="css/style.css" rel='stylesheet' type='text/css'/>
    <!--webfonts-->
    <link href='http://fonts.useso.com/css?family=PT+Sans:400,700,400italic,700italic|Oswald:400,300,700'
          rel='stylesheet' type='text/css'>
    <link href='http://fonts.useso.com/css?family=Exo+2' rel='stylesheet' type='text/css'>
    <!--//webfonts-->
    <script src="http://ajax.useso.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<script>$(document).ready(function (c) {
    $('.close').on('click', function (c) {
        $('.login-form').fadeOut('slow', function (c) {
            $('.login-form').remove();
        });
    });
});
</script>
<!--SIGN UP-->
<h1>管理員登錄</h1>
<div class="login-form">
    <div class="close"></div>
    <div class="head-info">
        <label class="lbl-1"> </label>
        <label class="lbl-2"> </label>
        <label class="lbl-3"> </label>
    </div>
    <div class="clear"></div>
    <div class="avtar">
        <img src="images/avtar.png"/>
    </div>
    <form action="${pageContext.request.contextPath}/loginServlet" method="post">
        <input type="text" name="administrators" class="text" value="Username" onfocus="this.value = '';"
               onblur="if (this.value == '') {this.value = 'Username';}">
        <div class="key">
            <input type="password" id ="password" name="password" value="Password" onfocus="this.value = '';"
                   onblur="if (this.value == '') {this.value = 'Password';}">
        </div>

        <%--<input type="text" name="checkcode" width="50px;"><img src="/hehewocao/checkCodeServlet" height="30px">--%>

        <div class="signin">
            <input type="submit" value="Login" >
        </div>
    </form>
</div>
<br>
<p align="center" style="color: red">
    <c:if test="${not empty login_msg}"><%--這裏回顯錯誤信息--%>
        ${login_msg}
    </c:if></p>
<div class="copy-rights">
    <p>Create By BOOM : [email protected]</p>
</div>
</body>
</html>

好了,到此就完成了管理員登錄的功能。
源碼在我的GitHub上:[email protected]:hehewocao00544/JavaEE.git

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章