1. 程式人生 > 實用技巧 >Java-JSP頁面實現簡單登入退出(僅供參考)

Java-JSP頁面實現簡單登入退出(僅供參考)

1、JSP頁面程式碼

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"> 
<meta name="viewport" content="width=device-width, initial-scale=1
"> <link rel="stylesheet" type="text/css" href="./css/login/normalize.css" /> <link rel="stylesheet" type="text/css" href="./css/login/demo.css" /> <link rel="stylesheet" type="text/css" href="./css/login/component.css" /> <title>登入</title> </head> <body> <body> <div class
="container demo-1"> <div class="content"> <div id="large-header" class="large-header"> <canvas id="demo-canvas"></canvas> <div class="logo_box"> <h3>登入</h3> <form action="
${pageContext.request.contextPath }/login/loginyy" name="f" method="post"> <div class="input_outer"> <span class="u_user"></span> <input id="username" name="username" value="" class="text" style="color: #FFFFFF !important" type="text" placeholder="請輸入賬戶"> </div> <div class="input_outer"> <span class="us_uer"></span> <input id="password" name="password" value="" class="text" style="color: #FFFFFF !important; position:absolute; z-index:100;" type="password" placeholder="請輸入密碼"> </div> <div class="mb2"> <!-- <a class="act-but submit" href="${pageContext.request.contextPath }/login/loginyy" style="color: #FFFFFF"> --> <input class="text" type="submit" value="登入" style="color: #FFFFFF"> </a> </div> </form> </div> </div> </div> </div><!-- /container --> <script src="./js/login/TweenLite.min.js"></script> <script src="./js/login/EasePack.min.js"></script> <script src="./js/login/rAF.js"></script> <script src="./js/login/demo-1.js"></script> <div style="text-align:center;"> </div> </body> </html>

2、建立登入使用者User實體類

package com.chao.entity;

public class User {
    private String username;
    private String password;

    public String getUsername() {
        return this.username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return this.password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

3、mysql資料庫連線池

package com.chao.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBUtil {
    private String dbUrl = "jdbc:mysql://資料庫ip地址:3306/login";
    private String dbUserName = "資料庫使用者名稱";
    private String dbPassword = "資料庫登入密碼";
    private String jdbcName = "com.mysql.cj.jdbc.Driver";

    public Connection getCon() throws ClassNotFoundException, SQLException {
        Class.forName(this.jdbcName);
        Connection con = DriverManager.getConnection(this.dbUrl, this.dbUserName, this.dbPassword);
        return con;
    }

    public void closeCon(Connection con) throws SQLException {
        if (con != null)
            con.close();
    }
}

4、登入程式碼實現

package com.chao.controller;

import com.chao.entity.User;
import com.chao.utils.DBUtil;
import com.chao.utils.StringUtil;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping({ "login" })
public class LoginController {
    @RequestMapping
    public String toLoginIndex(Model model) {
        return "login";
    }

    @RequestMapping({ "loginyy" })
    public void toLogin(HttpServletRequest request, HttpServletResponse response) {
        User user = new User();
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        user.setUsername(username);
        user.setPassword(password);
        System.out.println("----------------" + username + "--" + password + "---------------");

        if ((StringUtil.isEmpty(password)) || (StringUtil.isEmpty(username))) {
            HttpSession session = request.getSession();
            session.setAttribute("error", "不能為空");
            try {
                response.sendRedirect(request.getContextPath() + "/login");
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("---------kong----------");
            return;
        }

        DBUtil db = new DBUtil();
        String sql = "select username from users where username='" + user.getUsername() + "'";
        String sql1 = "select password from users where password='" + user.getPassword() + "'";
        try {
            Statement stmt = db.getCon().createStatement();
            Statement stmt1 = db.getCon().createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            ResultSet rs1 = stmt1.executeQuery(sql1);

            if ((rs.next()) && (rs1.next())) {
                HttpSession session = request.getSession();
                session.setAttribute("currentUser", "登陸成功");
                response.sendRedirect("/file");
            } else {
                System.out.println("-------使用者名稱或密碼錯誤-----");

                HttpSession session = request.getSession();
                session.setAttribute("error", "錯誤");
                session.setAttribute("username", username);
                session.setAttribute("password", password);

                response.setCharacterEncoding("GB2312");
                PrintWriter out = response.getWriter();
                out.print("<script>alert('使用者名稱或密碼錯誤,請重新輸入!'); window.location='/login' </script>");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

5、JSP頁面直接跳轉攔截驗證

<%
    if(null==session.getAttribute("currentUser")){
        System.out.print("ddd");
        response.sendRedirect("/login");
        return;
    }else{
        System.out.print("yyy");
    }
 %>