1. 程式人生 > >JavaWeb使用者登入功能的實現

JavaWeb使用者登入功能的實現

大四快畢業了,3年多的時間中,亂七八糟得學了一大堆,想趁找工作之前把所學的東西整理一遍,所以就嘗試著做一個完整的javaWeb系統,這幾天試著做了一個使用者登入的功能,分享給大家,肯定有很多不完善的地方,希望大家提提寶貴的意見,必將努力完善它。
我貼出此篇部落格的目的是,將一些以後有可能用到的重複性的程式碼儲存下來,用於以後需要時直接複製貼上,所以,此篇部落格大部分都是程式碼,講解性的語句並不多,如果大家看得頭疼,不如不看,以後萬一用到的話再拿過來修修改改即可。
有可能用得到的部分:生成驗證碼的Java類、操作資料庫的Java類
使用者登入模組採用了多種語言:
HTML、css、query:頁面
Servlet、java:後臺
執行效果圖:
在這裡插入圖片描述


Login.html程式碼:

登入介面 登入 JQuery程式碼:login.js

$(function(){
$(".loginform_submit").click(function(){
if(checkInput()) {
$(“form”).action("/loginServlet");
}else{
return false;
}
});
$(".validationCode_img").click(function(){
KaTeX parse error: Expected 'EOF', got '}' at position 93: …random()); }̲); functio…

(“input[name=username]”).val() == null || $(“input[name=username]”).val() == “”){
alert(“使用者名稱不能為空”);
KaTeX parse error: Expected 'EOF', got '}' at position 71: …alse; }̲ //判斷密…(“input[name=password]”).val() == null || $(“input[name=password]”).val() == “”){
alert(“密碼不能為空”);
KaTeX parse error: Expected 'EOF', got '}' at position 71: …alse; }̲ //判斷驗…
(“input[name=validationCode]”).val() == null || $(“input[name=validationCode]”).val() == “”){
alert(“驗證碼不能為空”);
$(“input[name=validationCode]”).focus();
return false;
}
return true;
}
});
生成驗證碼的Servlet:ValidationCode.java
package zh.userlogin.sample;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
/**

  • Created by zhang on 2014/9/13.
    /
    public class ValidationCode extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //獲得驗證碼集合的長度
    int charsLength = codeChars.length();
    //下面3條記錄是關閉客戶端瀏覽器的緩衝區
    //這3條語句都可以關閉瀏覽器的緩衝區,但是由於瀏覽器的版本不同,對這3條語句的支援也不同
    //因此,為了保險起見,同時使用這3條語句來關閉瀏覽器的緩衝區
    resp.setHeader(“ragma”, “No-cache”);
    resp.setHeader(“Cache-Control”, “no-cache”);
    resp.setDateHeader(“Expires”, 0);
    //設定圖形驗證碼的長和寬
    int width = 90, height = 30;
    BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
    Graphics g = image.getGraphics(); //獲得用於輸出文字的Graphics物件
    Random random = new Random();
    g.setColor(getRandomColor(180, 250));
    g.fillRect(0, 0, width, height);
    g.setFont(new Font(“Times New Roman”,Font.ITALIC,height));
    g.setColor(getRandomColor(120, 180));
    //使用者儲存最後隨機生成的驗證碼
    StringBuilder validationCode = new StringBuilder();
    //驗證碼的隨機字型
    String[] fontNames = {“Times New Roman”,“Book antiqua”,“Arial”};
    //隨機生成4個驗證碼
    for(int i = 0; i < 4; i++){
    //隨機設定當前驗證碼的字元的字型
    g.setFont(new Font(fontNames[random.nextInt(3)],Font.ITALIC,height));
    //隨機獲得當前驗證碼的字元
    char codeChar = codeChars.charAt(random.nextInt(charsLength));
    validationCode.append(codeChar);
    //隨機設定當前驗證碼字元的顏色
    g.setColor(getRandomColor(10, 100));
    //在圖形上輸出驗證碼字元,x和y都是隨機生成的
    g.drawString(String.valueOf(codeChar), 16
    i + random.nextInt(7), height-random.nextInt(6));
    }
    //獲得HttpSession物件
    HttpSession session = req.getSession();
    //設定session物件5分鐘失效
    session.setMaxInactiveInterval(560);
    //將驗證碼儲存在session物件中,key為validation_code
    session.setAttribute(“validation_code”, validationCode.toString());
    //關閉Graphics物件
    g.dispose();
    OutputStream outS = resp.getOutputStream();
    ImageIO.write(image, “JPEG”, outS);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doGet(req,resp);
    }
    //圖形驗證碼的字符集,系統將隨機從這個字串中選擇一些字元作為驗證碼
    private static String codeChars = “0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ”;
    //返回一個隨機顏色
    private static Color getRandomColor(int minColor, int maxColor){
    Random random = new Random();
    if(minColor > 255){
    minColor = 255;
    }
    if(maxColor > 255){
    maxColor = 255;
    }
    //獲得r的隨機顏色值
    int red = minColor + random.nextInt(maxColor-minColor);
    //g
    int green = minColor + random.nextInt(maxColor-minColor);
    //b
    int blue = minColor + random.nextInt(maxColor-minColor);
    return new Color(red,green,blue);
    }
    }
    操作資料庫的程式碼:ManageSQLServer2008.java(本人使用的資料庫為SQLServer 2008)
    package zh.userlogin.sample.dbmanager;
    import java.beans.Statement;
    import java.sql.
    ;
    public class ManageSQLServer2008 {
    //資料庫的驅動名
    private final String dbDriver = “com.microsoft.sqlserver.jdbc.SQLServerDriver”;
    //資料庫的url地址
    private final String url = “jdbc:sqlserver://localhost:1433;databaseName=zhDemo”;
    private final String userName = “sa”;
    private final String password = “123”;
    private Connection conn = null;
    public ManageSQLServer2008(){
    //載入資料庫驅動
    try {
    Class.forName(dbDriver).newInstance();
    //System.out.println(“載入驅動成功”);
    } catch (Exception e) {
    e.printStackTrace();
    System.err.println(“資料庫驅動載入失敗”);
    }
    //獲取資料庫連結
    try {
    conn = DriverManager.getConnection(url,userName,password);
    } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    System.err.println(“獲取資料庫連結失敗”);
    }
    }
    //執行各種SQL語句的方法
    private ResultSet execSQL(String sql,Object… args) throws SQLException{
    //建立PreparedStatement物件
    PreparedStatement pStmt = conn.prepareStatement(sql);
    //為pStmt物件設定SQL引數值
    for(int i = 0; i < args.length; i++){
    pStmt.setObject(i+1, args);
    }
    //執行SQL語句
    pStmt.execute();
    //返回結果集,如果執行的SQL語句不返回結果集,則返回null
    return pStmt.getResultSet();
    }
    private void closeSQLConn(){
    //關閉資料庫連結
    if(conn != null){
    try {
    conn.close();
    } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }
    public String checkUser(String username,String password){
    boolean has_username = false;
    boolean password_correct = false;
    ResultSet rs = null;
    try {
    rs = execSQL(“select * from zh_users”);
    } catch (SQLException e) {
    System.err.println(“查詢資料庫出錯”);
    e.printStackTrace();
    return null;
    }
    try {
    while(rs.next()){
    String temp_username = rs.getString(“user_name”).trim();
    String temp_password = rs.getString(“password_md5”).trim();
    if(username.equals(temp_username)){
    has_username = true;
    if(password.equals(temp_password)){
    password_correct = true;
    return “hasUserNameAndPasswordCorrect”;
    }
    return “hasUserNameButPasswordInCorrect”;
    }
    }
    } catch (SQLException e) {
    System.err.println(“操作ResultSet出錯”);
    e.printStackTrace();
    }
    return “hasNoUserName”;
    }
    }
    用於處理使用者登入的Servlet:LoginServlet.java
    package zh.userlogin.sample;
    import zh.userlogin.sample.dbmanager.ManageSQLServer2008;
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    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.io.OutputStream;
    /**
  • Created by zhang on 2014/9/13.
    */
    public class LoginServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    OutputStream out = resp.getOutputStream();
    String username = req.getParameter(“username”);
    String password = req.getParameter(“password”);
    String validationCode = req.getParameter(“validationCode”);
    HttpSession session = req.getSession();
    String validation_code = (String)session.getAttribute(“validation_code”);
    if(validationCode.equalsIgnoreCase(validation_code)){
    System.out.println(“驗證碼正確”);
    }else{
    System.out.println(“驗證碼錯誤”);
    }
    ManageSQLServer2008 mss = new ManageSQLServer2008();
    String result = mss.checkUser(username,password);
    if (result.equals(“hasUserNameAndPasswordCorrect”)) {
    System.out.println(“使用者名稱和密碼均正確”);
    } else if (result.equals(“hasUserNameButPasswordInCorrect”)) {
    System.out.println(“使用者名稱正確,密碼不正確”);
    } else if (result.equals(“hasNoUserName”)) {
    System.out.println(“沒有此使用者”);
    }
    //轉發到result.jsp
    RequestDispatcher rd = req.getRequestDispatcher(“Login.html”);
    rd.forward(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doGet(req,resp);
    }
    }
    web.xml檔案的配置:

    loginServlet
    zh.userlogin.sample.LoginServlet


    loginServlet
    /loginServlet


    validationCode
    zh.userlogin.sample.ValidationCode


    validationCode
    /validationCode

    最後的style.css程式碼,太多了,而且有點亂,所以就沒有貼出來,至於CSS程式碼,大家可以去網上下載:http://sc.chinaz.com/tag_moban/htmlMoBan.html這個上面就有好多,大家根據喜好選擇一個,然後稍加即可。