JavaWeb用户登录功能的实现

原文地址为: JavaWeb用户登录功能的实现

    大四快毕业了,3年多的时间中,乱七八糟得学了一大堆,想趁找工作之前把所学的东西整理一遍,所以就尝试着做一个完整的JavaWeb系统,这几天试着做了一个用户登录的功能,分享给大家,肯定有很多不完善的地方,希望大家提提宝贵的意见,必将努力完善它。

    我贴出此篇博客的目的是,将一些以后有可能用到的重复性的代码保存下来,用于以后需要时直接复制粘贴,所以,此篇博客大部分都是代码,讲解性的语句并不多,如果大家看得头疼,不如不看,以后万一用到的话再拿过来修修改改即可。

    有可能用得到的部分:生成验证码的Java类、操作数据库的Java类

用户登录模块采用了多种语言:

Html、css、query:页面

Servlet、java:后台

运行效果图:

wpsB3BB.tmp

Login.html代码:

<!DOCTYPE html>

<html>

<head lang="en">

    <meta charset="UTF-8">

    <title>登录界面</title>

    <script src="js/jquery-1.11.1.js"></script>

    <script src="js/login.js"></script>

    <link href="css/style.css" rel="stylesheet" type="text/css" />

</head>

<body>

    <div id="loginpanelwrap">

        <div class="loginheader">

            <div class="logintitle">登录</div>

        </div>

        <form action = "/UserLogin/Sample1/loginServlet">

            <div class="loginform">

                <div class="loginform_row">

                    <label>用户名:</label>

                    <input type="text" class="loginform_input" name="username" />

                </div>

                <div class="loginform_row">

                    <label>密码:</label>

                    <input type="password" class="loginform_input" name="password" />

                </div>

                <div class = "loginform_row">

                    <label>验证码:</label>

                    <input type = "text" class="loginform_input_validationCode" name = "validationCode"/>

                    <img class = "validationCode_img" src="/UserLogin/Sample1/validationCode">

                </div>

                <div class="loginform_row">

                    <span class = "returnInfo"></span>

                    <input type="submit" class="loginform_submit" value="登录" />

                </div>

                <div class="clear"></div>

            </div>

        </form>

    </div>

</body>

</html>

JQuery代码:login.js

 

$(function(){

   $(".loginform_submit").click(function(){

       if(checkInput()) {

           $("form").action("/loginServlet");

       }else{

           return false;

       }

   });

   $(".validationCode_img").click(function(){

       $(".validationCode_img").attr("src","/UserLogin/Sample1/validationCode?"+Math.random());

   });

    function checkInput(){

        //判断用户名

        if($("input[name=username]").val() == null || $("input[name=username]").val() == ""){

            alert("用户名不能为空");

            $("input[name=username]").focus();

            return false;

        }

        //判断密码

        if($("input[name=password]").val() == null || $("input[name=password]").val() == ""){

            alert("密码不能为空");

            $("input[name=password]").focus();

            return false;

        }

        //判断验证码

        if($("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(5*60);

        //将验证码保存在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[i]);

        }

        //执行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文件的配置:

<servlet>

        <servlet-name>loginServlet</servlet-name>

        <servlet-class>zh.userlogin.sample.LoginServlet</servlet-class>

    </servlet>

    <servlet-mapping>

        <servlet-name>loginServlet</servlet-name>

        <url-pattern>/loginServlet</url-pattern>

    </servlet-mapping>

    <servlet>

        <servlet-name>validationCode</servlet-name>

        <servlet-class>zh.userlogin.sample.ValidationCode</servlet-class>

    </servlet>

    <servlet-mapping>

        <servlet-name>validationCode</servlet-name>

        <url-pattern>/validationCode</url-pattern>

</servlet-mapping>

最后的style.css代码,太多了,而且有点乱,所以就没有贴出来,至于CSS代码,大家可以去网上下载:http://sc.chinaz.com/tag_moban/htmlMoBan.html这个上面就有好多,大家根据喜好选择一个,然后稍加即可。


转载请注明本文地址: JavaWeb用户登录功能的实现