Hi HacH:
Tarwn code is excellent for your application. You must improve it if you plan to use it in production. There are some corrections I would made:
1) "SELECT * FROM UserTable WHERE user_name = '" + strUsername + "' AND user_pass = '" + strPassword + "'"
Check this query:
SELECT * FROM UserTable WHERE user_name = 'anything' AND user_pass = '' OR ''=''
This would be true for any database, so a hacker just have to put:
' OR ''='
in the password field to access your application.
You can avoid this using another authentication mechanism (LDAP or something similar) or using java.sql.PreparedStatement to access the database.
2) It's not good to have business code embedded in a JSP page, as a matter of design patterns. You can see a detailed explanation of this issue in another thread answered by me. It is better for you to use a Session Bean to perform the authentication and mantain session information to show the content to an specific user.
you can use a bean which is a simple class with the jsp directive:
<%@ page import="ClassName" %>
<jsp:useBean id="className" scope="session" class="ClassName" />
You can use the bean methods in the jsp like:
className.method();
---------------
Now, the connection to the database, could be made through the jdbc conectivity. If you are using access, one way is to use the jdbc-odbc bridge. You can set an ODBC source in the configuration Panel and then point a java.sql.Connection to this source through the jdbc.odbc driver. check this example:
Code:
database.properties:
driver=sun.jdbc.odbc.JdbcOdbcDriver
jdbc=jdbc:odbc:YOUR_SOURCE_NAME
user=
passwd=
Connection Bean:
private static String driver;
private static String jdbc;
private static String user;
private static String passwd;
private static void getResources(){
try{
resources=ResourceBundle.getBundle("database");
driver=resources.getString("driver");
jdbc=resources.getString("jdbc");
user=resources.getString("user");
passwd=resources.getString("passwd");
}
catch(MissingResourceException e){
ex.show("No se encuentra el recurso:",e);
}
catch(Exception e){
ex.show("Excepcion no reconocida:",e);
}
}
private static void conectar(){
try{
Class.forName(driver);
}
catch(ClassNotFoundException e){
ex.show("No se encuentra el driver especificado:",e);
}
catch(Exception e){
ex.show("Excepcion no reconocida:",e);
}
try{
conexion = DriverManager.getConnection(jdbc,user,passwd);
metaData=conexion.getMetaData();
}
catch(SQLException e){
ex.show("No se puede obtener la conexion:",e);
}
catch(Exception e){
ex.show("Excepcion no reconocida:",e);
}
System.out.println("Conexion realizada. ID: "+conexion);
}
Feel free to post back if you have any more questions.
Hope it helps.
Pedro Andrés Solorzano
Pontificia Universidad Javeriana
Bogotá, Colombia, SurAmérica.