我有一个java类,它充当登录页面并与微软访问连接,工作正常。我的问题是,我试图使用相同的功能,但在JSP页面上,有关如何做到这一点的任何想法?尝试了一些事情,没有任何作用。
我当前连接到数据库的login.java背后的代码如下:
package com;
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
import java.applet.*;
public class login extends Applet {
Connection con;
Statement st;
ResultSet rs;
JFrame f = new JFrame("User Login");
JLabel l = new JLabel("Username:");
JLabel l1 = new JLabel("Password:");
JTextField t = new JTextField(10);
JTextField t1 = new JTextField(10);
JButton b = new JButton("login");
public login(){
connect();
frame();
}
public void connect()
{
try{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:AngelsAndDemons";
con = DriverManager.getConnection(db);
st = con.createStatement();
}
catch(Exception ex)
{
}
}
private void frame()
{
f.setSize(600,400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
JPanel p = new JPanel();
p.add(l);
p.add(t);
p.add(l1);
p.add(t1);
p.add(b);
f.add(p);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
try{
String user = t.getText().trim();
String pass = t1.getText().trim();
String sql = "select user,pass from AngelsAndDemons where user = '"+user+"'and pass = '"+pass+"'";
rs = st.executeQuery(sql);
int count = 0;
while(rs.next())
{
count = count + 1;
}
if(count == 1)
{
JOptionPane.showMessageDialog(null,"User found, Access Granted!");
}
else if(count > 1){
JOptionPane.showMessageDialog(null,"Duplicte User, Access Denied");
}
else{
JOptionPane.showMessageDialog(null,"User not found");
}
}
catch(Exception ex)
{
}
try{
String user = t.getText().trim();
String pass = t1.getText().trim();
String sql = "select user,pass from AngelsAndDemons where user = '"+user+"'and pass = '"+pass+"'";
rs = st.executeQuery(sql);
int count = 0;
while(rs.next())
{
count = count + 1;
}
if(count == 1)
{
JOptionPane.showMessageDialog(null,"User found, Access Granted!");
}
else if(count > 1){
JOptionPane.showMessageDialog(null,"Duplicte User, Access Denied");
}
else{
JOptionPane.showMessageDialog(null,"User not found");
}
}
catch(Exception ex)
{
}
}
});
}
public static void main(String[] args){
new login();
}
}//END CLASS
答案 0 :(得分:0)
JSP有一个简单的语法来连接和检索数据库中的数据,你可以尝试
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<sql:setDataSource var="tableImage" driver="sun.jdbc.odbc.JdbcOdbcDriver"
url="jdbc:mysql://localhost/database"
user="userName" password="userPassword"/>
<sql:query dataSource="${tableImage}" var="queryResult">
SELECT * from Table;
</sql:query>
最后打印线
<c:forEach var="oneRow" items="${queryResult.rows}">
<c:out value="${oneRow.column}"/>