鏈接oracle數據庫,新建用戶登陸界面

一.下載jar包

下載oracle驅動包:ojdbc6.jar,放於以下位置:

測試代碼:javascript

package com.test;

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

import org.junit.Test;

public class Test01 {

    @Test
    public void test() {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection conn = null;
            //orcl 是數據庫名;test123是用戶名;qwer1234是密碼
            conn = DriverManager.getConnection(
                    "jdbc:oracle:thin:@localhost:1521:orcl", "test123",
                    "qwer1234");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

運行成功就算鏈接成功了,以後就能夠操做數據庫了。
參考地址:https://blog.csdn.net/he__xu/article/details/83410966
jar包下載連接:https://pan.baidu.com/s/1j2lV7uJWsgmW0yym9j8jHw 提取碼:0mqkhtml

2、使用spring框架:

1.須要下載:

commons-dbcp jar包:
下載地址:http://commons.apache.org/proper/commons-dbcp/download_dbcp.cgi
連接:https://pan.baidu.com/s/1BsbXz1FG4FQi4-ZSIWnYhQ 提取碼:d3uo
commons-pool jar包:
下載地址:http://commons.apache.org/proper/commons-pool/download_pool.cgi
連接:https://pan.baidu.com/s/1LTK2WQ1CIsIglYqVZBr6ig 提取碼:38v8
連接:https://pan.baidu.com/s/1O6cI7FOtlMYyzzYDX4phcQ 提取碼:b3snjava

2.web.xml配置:

<!--配置數據源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
        <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"/>
        <property name="username" value="test123"/>
        <property name="password" value="qwer1234"/>
        <!-- 鏈接池啓動時的初始值 -->
        <property name="initialSize" value="3" />
        <!-- 鏈接池的最大值 -->
        <property name="maxActive" value="300" />
        <!-- 最大空閒值.當通過一個高峯時間後,鏈接池能夠慢慢將已經用不到的鏈接慢慢釋放一部分,一直減小到maxIdle爲止 -->
        <property name="maxIdle" value="2" />
        <!-- 最小空閒值.當空閒的鏈接數少於閥值時,鏈接池就會預申請去一些鏈接,以避免洪峯來時來不及申請 -->
        <property name="minIdle" value="1" />
        <!-- end -->
</bean>

3.測試代碼:

@Test
    public void test() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext(
                "resource/applicationContext.xml");
    }

備註:若是有如下報錯:
警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource': Failed to introspect bean class [org.apache.commons.dbcp.BasicDataSource] for lookup method metadata: could not find class that it depends on; nested exception is java.lang.NoClassDefFoundError: org/apache/commons/pool/ObjectPool
能夠把commons-pool2-2.4.3.jar須要換成commons-pool-1.6.jarweb

3、調用測試:

代碼:spring

public void test() {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("resource/applicationContext.xml");
    BasicDataSource dataSource = (BasicDataSource) ctx.getBean("dataSource");
}


解決:在aop後面添加一個屬性:proxy-target-class="true"

測試經過後直接試着調用一下
代碼:sql

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        ApplicationContext ctx = new ClassPathXmlApplicationContext("resource/applicationContext.xml");

        BasicDataSource dataSource = (BasicDataSource) ctx.getBean("dataSource");
        String msg = "";
        Statement st = null;
        ResultSet rs = null;

        try {
            // 一、獲取鏈接對象
            Connection conn = dataSource.getConnection();
            // 二、建立statement類對象,用來執行SQL語句!!
            st = conn.createStatement();
            // 三、建立sql查詢語句
            String sql = "select * from sys_user ";
            // 四、執行sql語句而且換回一個查詢的結果集
            rs = st.executeQuery(sql);
            while (rs.next()) { // 循環遍歷結果集
                int id = rs.getInt("user_id");
                String name = rs.getString("real_name");
                msg += "id=" + id + "--" + "name=" + name+"<br>";
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html><head><title>一二零叄的網站</title></head><body>");
        out.print(msg);
        out.print("</body></html>");
    }

其中用戶表:

結果:
數據庫

4、使用配置文件

1.jdbc.properties:

jdbc.driver=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:orcl
jdbc.username=test123
jdbc.password=qwer1234

2.web.xml改成:

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
        <property name="locations"> 
        <list> <value>classpath:resource/jdbc.properties</value> 
        </list> 
        </property> 
    </bean> 
    
    <!--配置數據源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <!-- 鏈接池啓動時的初始值 -->
        <property name="initialSize" value="3" />
        <!-- 鏈接池的最大值 -->
        <property name="maxActive" value="300" />
        <!-- 最大空閒值.當通過一個高峯時間後,鏈接池能夠慢慢將已經用不到的鏈接慢慢釋放一部分,一直減小到maxIdle爲止 -->
        <property name="maxIdle" value="2" />
        <!-- 最小空閒值.當空閒的鏈接數少於閥值時,鏈接池就會預申請去一些鏈接,以避免洪峯來時來不及申請 -->
        <property name="minIdle" value="1" />
        <!-- end -->
</bean>

這樣就能夠了。apache

5、簡單的用戶登陸

1.登陸界面login.jsp:

<%@ page language="java" import="java.util.*" 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=utf-8">
<title>一二零叄的網站</title>
<script type="text/javascript">
function zhuce(){
    alert("跳轉到註冊界面......");
}
</script>
</head>
<body>
    <center>
        <h1 style="color:#7D26CD">登陸</h1>
        <hr style="width:85%">
        <form id="indexform" name="indexForm" action="logincheck.jsp"
            method="post">
            <table border="0">
                <tr>
                    <td>帳號:</td>
                    <td colspan="2"><input type="text" name="username">
                    </td>
                </tr>
                <tr>
                    <td>密碼:</td>
                    <td colspan="2"><input type="password" name="password">
                    </td>
                </tr>
                <tr>
                    <td colspan="3" align="center">
                        <br> 
                        <input type="submit" value="登陸" style="color:#BC8F8F">
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <input type="button" onclick="zhuce()" value="註冊" style="color:#BC8F8F">
                    </td>
                </tr>
            </table>
        </form>
    </center>
</body>
</html>

2.登陸驗證:logincheck.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="java.lang.*"%>
<%@ page import="com.service.Login"%>
<%@ page import="net.sf.json.JSONObject"%>

<%
    try {
        request.setCharacterEncoding("UTF-8");
        String username = (String) request.getParameter("username");
        String password = (String) request.getParameter("password");//取出login.jsp的值
        Login login = new Login();
        JSONObject loginResult = login.checkLogin(username, password);
        if (1 == loginResult.getInt("status")) {
            response.sendRedirect("../IndexServlet");
        } else {
            out.print("<script language='javaScript'> alert('"
                    + loginResult.getString("msg") + "');</script>");
            response.setHeader("refresh", "0;url=login.jsp");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
%>

3.用戶驗證Login.java:

package com.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import net.sf.json.JSONObject;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Login {
    
    public JSONObject checkLogin(String username,String password){
        
        JSONObject result = new JSONObject();
        
        ApplicationContext ctx = new ClassPathXmlApplicationContext("resource/applicationContext.xml");

        BasicDataSource dataSource = (BasicDataSource) ctx.getBean("dataSource");
        PreparedStatement ps =null;

        try {
            // 一、獲取鏈接對象
            Connection conn = dataSource.getConnection();
            // 二、建立statement類對象,用來執行SQL語句!!
            ps = conn.prepareStatement("select password,enabled from sys_user where user_name = ? ");
            // 三、建立sql查詢語句
            ps.setString(1, username);
            // 四、執行sql語句而且換回一個查詢的結果集
            ResultSet rs = ps.executeQuery();
            if (rs.next()) { // 有查詢結果
                if(!password.equals(rs.getString("password"))){
                    result.put("status", "3");
                    result.put("msg", "密碼錯誤");
                } else if(1!=rs.getInt("enabled")){
                    result.put("status", "4");
                    result.put("msg", "改帳號不容許登陸");
                } else {
                    result.put("status", "1");
                    result.put("msg", "容許登陸");
                }
            } else {
                result.put("status", "2");
                result.put("msg", "不存在該帳號");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }
    
}

4.結果:

登陸界面:

登陸失敗:

登陸成功:
json

相關文章
相關標籤/搜索