登录界面---连接数据库

工程文件目录:

user数据库的login表:

代码:

login.jsp:

<%@ page contentType="text/html; charset=gb2312" pageEncoding="UTF-8"%>
<html>
    <head>
        <title>用户登录</title>
    </head>
    <body>
        <h2 align="center">用户登录</h2>
        <form name="form1" action="login_process.jsp" method="post"
                onsubmit="return isValidate(form1)">
                 <table align="center" border="0">
                    <tr>
                        <td>账号:</td>
                        <td><input type="text" name="username"></td>
                    </tr>
                    <tr>
                        <td>密码:</td>
                        <td><input type="password" name="password">
                        </td>
                    </tr>
                    <tr>
                    <td></td>
                        <td><input type="submit" value="登录"></td>
                    </tr>
                </table>                     
        </form>
    </body>
</html>

login_process.jsp:

<%@ page language="java" import="java.sql.*" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>登录中</title>
</head>
<body>
<%
    request.setCharacterEncoding("UTF-8");
    String driverStr = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    String connStr = "jdbc:sqlserver://localhost:1433; DatabaseName=user";
    String dbusername = "sa";
    String dbpassword = "4980";
     
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;    
    
    Class.forName(driverStr);
    conn = DriverManager.getConnection(connStr, dbusername, dbpassword);
    String sql = "select * from login where [username]=? and [password]=?";//定义一个查询语句
    stmt = conn.prepareStatement(sql);
    
    String user=(String)request.getParameter("username");
    String pass=(String)request.getParameter("password");//取出login.jsp的值
    stmt.setString(1, user);
    stmt.setString(2, pass);
    if(user.equals(""))
    {    
        out.print("<script language='javaScript'> alert('账号为空');</script>");
        response.setHeader("refresh", "0;url=login.jsp");
    }
    else if(pass.equals(""))
    {
        out.print("<script language='javaScript'> alert('密码为空');</script>");
        response.setHeader("refresh", "0;url=login.jsp");
    }
    
    
    rs = stmt.executeQuery();
    if(rs.next())
        response.sendRedirect("login_success.jsp");
    else 
    {
        out.print("<script language='javaScript'> alert('账号或密码错误');</script>");
        response.setHeader("refresh", "0;url=login.jsp");
    }
    
    stmt.close();
    conn.close();
%>
</body>
</html>

代码运行结果:

用户登录

账号:
密码:
 

 

posted @ 2017-02-24 22:07  丶枫  阅读(2317)  评论(0编辑  收藏  举报