JSP/Tomcat/MySQL

Hello JSP developers!
I have a problem trying to connect to MySQL database when I am doing a JSP or a servlet. I think the problem has to be with Tomcat, because when I do a java application with a database connection works perfectly, so there must be Tomcat.
I am working with Java j2sdk1.4.0 and Netbean as my IDE. When I compile the JSP under the IDE does not give me any errors but when I try to see the result with Tomcat 4.0 does not seem to recognize the mm.mysql driver and gives me the following errors:
Generated servlet error:
D:\Apache Tomcat 4.0\work\localhost\_\JspMySQL$jsp.java:75: Class org.apache.jsp.Connection not found.
Generated servlet error:
D:\Apache Tomcat 4.0\work\localhost\_\JspMySQL$jsp.java:76: Class org.apache.jsp.ResultSet not found.
     ResultSet results;
It gives me more errors, related to the connection. If you are willing to help me I can send you the exception report that Tomcat generates.
I would really appreciate if you help me about this issue, because I am beginnig to get frustated.
Thanks!!!!

It appears that your JspMySQL.jsp does not import the java.sql package. Try adding the following line at the top of the JSP:
<%@ page import="java.sql.*" %>

Similar Messages

  • How to combinate JSP+Tomcat+mysql??

    Hi,guys. My question is as the above subject.
    I have installed JDK, Tomcat, mysql, and my OS is WinXP, I am trying to develop a JSP site in my computer.
    For JDK, the commands javac, java, ...... work OK;
    For Tomcat, http://localhost:8080 works OK, meaning the cat page appears.
    For mysql, I can login, and sql statements work OK;
    And I download mysql-connector-java-3.1.8a.
    What I should do further to combinate JSP+Tomcat+mysql, so my JSP site can work? Any advice?
    I need help.
    Thanks in advance!

    Thanks,duffymo!
    As you said, I am learning more about those things.
    Actually I am trying to open a JSP webpage to show the connection JSP+Tomcat+mysql works OK.
    I copied the mysql-connector-java-3.1.8-bin.jar to ...Tomcat 5.0\common\lib,
    created a datebase, named test in MySQL, and wrote a JSP as the below:
    <%@ page contentType="text/html; charset=gb2312" %>
    <%@ page language="java" %>
    <%@ page import="com.mysql.jdbc.Driver" %>
    <%@ page import="java.sql.*" %>
    <%
    //driver
    String driverName="com.mysql.jdbc.Driver";
    //username
    String userName="test";
    //code
    String userPasswd="123";
    //database
    String dbName="test";
    //table name
    String tableName="mytab";
    //connection string
    String url="jdbc:mysql://localhost/"+dbName+"?user="+userName+"&password="+userPasswd;
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    Connection connection=DriverManager.getConnection(url);
    Statement statement = connection.createStatement();
    String sql="SELECT * FROM "+tableName;
    ResultSet rs = statement.executeQuery(sql);
    ResultSetMetaData rmeta = rs.getMetaData();
    int numColumns=rmeta.getColumnCount();
    // output
    out.print("id");
    out.print("|");
    out.print("num");
    out.print("<br>");
    while(rs.next()) {
    out.print(rs.getString(1)+" ");
    out.print("|");
    out.print(rs.getString(2));
    out.print("<br>");
    out.print("<br>");
    out.print("successful!");
    rs.close();
    statement.close();
    connection.close();
    %>
    How can I test the connection JSP+Tomcat+mysql works OK?
    Thanks again!

  • Tomcat / MySQL problem

    Simple Tomcat / MySQL code works well on the development server (Windows) but crashes on the production server (Linux).
    It finds and loads the driver, then fails to create a connection with
    java.security.AccessControlException: access denied (java.net.SocketPermission localhost resolve)Driver is mysql-connector-java-3.0.14-production-bin.jar in ${catalina.home}/common/lib.
    MySQL is version 3.23.58.
    Tomcat version 4.1.29.
    Java version 1.4.2_02.
    Operating system is RedHat 9 with Plesk 7.
    This looks like a Tomcat security issue but catalina.policy grants all permissions to ${catalina.home}/common/lib/-.
    Granting specific permissions has made no difference:
    grant codeBase "file:${catalina.home}/common/lib/mysql-connector-java-3.0.14-production-bin.jar" {
      permission java.net.SocketPermission "localhost:3306", "listen,connect,accept,resolve";
    };The code is straight from the Java tutorial, presented three ways:
    1. in a bean, called from a JSP
    2. inline in a JSP
    3. in a JAR, as an executable class
    All of these work in Windows. Only No 3 works in Linux (which suggests the issue is not with Java security). Other JSP pages work fine.
    I have not found a MySQL driver preinstalled on the system. I first added mysql-connector-java-3.1.10-bin.jar but this failed because it could not read charset mappings. I have
    now reverted to mysql-connector-java-3.0.14-production-bin.jar. Adding the JAR in application/WEB-INF/lib does not help.
    I wonder if there is a class loader issue but I cannot find any other JARs that conflict.
    Could Tomcat be trying to connect on a different port? It makes no difference whether or not the port number (3306) is included in the URL.
    Granting permissions for IP addresses and domain names makes no difference (so far). Besides, the error message is specific about localhost.
    Can anyone help, please?
    Many thanks
    Robin

    Spot on! I am not at all clear whether the root cause of the problem is Tomcat, MySQL, Java or whatever ... Until I understand more, everything is suspect.
    I have been asking myself what can cause this Access denied / SocketPermission error?
    - mis-configuration of the permission: codebase, url, port ?
    - in the wrong policy file? catalina.policy or java.policy ?
    - faulty installation of something?
    - incompatible versions ?
    The code all works well on the development machine, which runs Windows 2000. Running it on the Linux machine causes problems.
    I do not have full control of the configuration of the Linux machine but I am able to restart Tomcat when needed.
    Some specific questions:
    I know from the stack trace which Java function is being called:
    java.sql.DriverManager.getConnection()The MySQL driver is checking for socket permission when it tries to get a connection and throws:
    java.security.AccessControlException: access denied (java.net.SocketPermission localhost resolve) - How do I tell what parameters are being passed to getConnection() without installing the source code?
    - How do I tell for sure which policy file governs the check?
    Many thanks
    Robin

  • PleaseHelp on jsp and Mysql connectivity and a lot of exception errors

    Hi,
    I am Trying to connect a JSP page with Mysql database. I am having a lot of probelms. After having a lot of problems in connecting the JSp with Mysql. Intilally it was giving me the exception error that " NO appropriate driver was found. After modifying the URl it was fine. Now It is giving the Following errors.
    servlet.ServletException: Communication link failure: java.io.IOException, underlying cause: Unexpected end of input stream ** BEGIN NESTED EXCEPTION ** java.io.IOException MESSAGE: Unexpected end of input stream
    In a window before loading the Explorer page it is giving the following error that The port 8081 is already in use and i should expand to other ports. Noraml JSP Files which used to work before are also not working .
    Internal Tomcat JWSDP is alos not working. If i try to start the server it says that port 8081 is already in USe . A java.net.connection exception is also occuring. The normal JSP files are also not working. What is Happening. I am also giving the code i have writted. PLease tellme why so many exception errors are occuring.
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:8081/mis_project", "root", " ");
    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery("Select study_semester FROM Semester");
    while(rs.next()) {
    %>
    <option value="<%= rs.getString("Study_Semester") %>">
    </option>
    <% }
    if(rs!=null) rs.close();
    if(stmt!=null) stmt.close();
    if(con!=null) con.close();
    I am trying to connect to Mysql and automatocally populate a field in a Form in later JSp pages i intend to record the data entered in these fields into other tables.

    <%
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/myDB?user=username&password=mypass");
    Statement stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
    String cat = "";
              try{
              cat = request.getParameter("category");
              }catch(NullPointerException npe){}
              ResultSet rs = stmt.executeQuery("SELECT id,fullname FROM users WHERE category LIKE '%motor%' AND subcategory like '%"+cat+"%'");
         %>
    This piece gets a category parameter from a form post and uses it to search for a specific category in a database table. I think maybe u need to download JConnector from mysql site and unzip it to the classes folder of your WEB-INF in Tomcat server...... i hope this helps a bit

  • JSP and MySql Connectivity in Fedora core 4

    Dear all,
    We are developing software using JSP and MySql on Fedora Core 4 platform and are unable to find the connectivity for JSP and MySql. Can anybody help....

    Dear all,
    We are developing software using JSP and MySql on Fedora Core 4 platform and are unable to find the connectivity for JSP and MySql. Can anybody help....

  • JSP with MYSQL 4.0

    May i know is JSP works well with MYSQL 4.0 database?

    Yaah..it works perfectly OK....just download the required driver my mysql site only & ur ready to develop applications is JSP using mysql.

  • Unable to connect JSP and MySQL

    Hi, I am new to this forum
    I've started developing web pages using JSP
    I've the problem connecting JSP and MySQL database. I've created the page that retrive records from mysql table. But the connection fail to access to database it gives me this error:
    org.apache.jasper.JasperException: Exception in JSP: /retreive_book.jsp:15
    The code is:
    12: <%
    13: //Class.forName("com.mysql.jdbc.Driver").newInstance();
    14: Class.forName("org.gjt.mm.mysql.Driver");
    15: connection = DriverManager.getConnection(connectionURL,"","");
    16: statement = connection.createStatement();
    17: rs = statement.executeQuery("SELECT * FROM books_detail");
    18: %>
    And the connectionURL parameter has this value:
    String connectionURL = "jdbc:mysql://localhost:3306/books?username=;password=";
    root cause msg is:
    java.sql.SQLException: Invalid authorization specification: Access denied for user 'nobody'@'localhost' (using password: NO)
    Please can anyone help me. It is 3 days now trying to do that but not succeded yet

    Hi
    Yes It is true that my MySQl installation its username is root. So how should put that in the url. Cause I did that but it didn.t work
    String connectionURL= "jdbc:mysql://localhost:3306/books?username=root;password=";
    If I write in that manner is it correct for root username or should I put a single quote
    Thanks

  • How to create table with jsp in mysql

    Hi, every one,
    I just want to know how to create a table with jsp in mysql, please.
    Thanks in advance

    I have got the same question. I tried to pass sql "Create table" statement, but the servlet engine (tomcat4) threw an error "could not manipulet statement.execute". It works for normal SQL select statement.
    Anyone got the same problem ? or got a solution for this ? someone told me that PHP can do it, but just want to get it works with JSP.

  • Catching jsp/tomcat/java SQL error

    I have been trying to get the sample code to work from an old book. I was finally able to get it to run under tomcat 4.1.31 but there is one bug I just cannot figure out how to handle. I am a beginner to Java/JSP/Tomcat and have about 16+ hours invested in this problem so far.
    The delFruit.jsp calls methods from FruitConnect.java.
    I found that if the fruit chosen for deletion was not involved in a referential integrity link to a FruitMonth file the code works fine. But if it is linked the delFruit.jsp just displays a blank screen and nothing is deleted. It is fine for it not to be deleted but I cannot find anyway to handle it. I tried to add the checkFruitForSale bandaid below but it causes me a blank screen as well.
    Any help would be appreciated.
    It would be great if I could just see what is happening when FruitConnect is processing code. I get no errors, just a blank screen. I'm going to try using NetBeans and their debugger next.
    Here is delFruit:
    <%@ page import="java.sql.*" %>
    <jsp:include page="adminHeader.html" flush="true" />
    <jsp:useBean id="fruitConnect" class="fruit1.FruitConnect" />
    <%
    String msg = "The following fruits have been deleted:<br> ";
    //Build the list of fruits to delete
    String delFruit[] = request.getParameterValues("delFruit");
    //WE WILL ONLY GET CHECKBOXES THAT WERE CHECKED
       String fruitList = "";
       if (delFruit != null){
         int len = delFruit.length;
         fruitConnect.dbConnect();
         for (int i = 0; i < len; i++) {
              String passfruit = delFruit;
              if (fruitConnect.checkFruitForSale(passfruit)) {}
              else{
              fruitList = fruitList + "'" + delFruit[i] + "',";
              msg = msg + delFruit[i] + "<br>";
              out.print(msg);
              out.print(msg);
         fruitList = fruitList + "'nonsense'";
         if (fruitConnect.deleteFruit(fruitList) < 1) {
              msg = "There was an error deleting the fruits from the database.";
         else{
         msg = "Deletion was successful";
         fruitConnect.dbDisconnect();
    else {
         msg = "You must select some fruit to delete.";
    %>
    HERE IS FruitConnect.java
    package fruit1;
    import java.sql.*;
    public class FruitConnect {
       private Driver drv = null;
       private Connection conn = null;
       private ResultSet rs = null;
       private Statement stmt = null;
       public FruitConnect(){}
       public void dbConnect() throws Exception{
    //      drv = (Driver) Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
    //      conn = DriverManager.getConnection("jdbc:odbc:Fruit");
    try{
          drv = (Driver) Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
          conn = DriverManager.getConnection("jdbc:odbc:Fruit");
    catch ( SQLException sqlException)
    sqlException.printStackTrace();
    finally
    try{
    catch (Exception exception)
       public boolean getNextItem() throws Exception{
          boolean ret = rs.next();
          return(ret);
       public String getItemNameString(String columnName) throws Exception{
          String name = rs.getString(columnName);
          return(name);
       public float getItemNameFloat(String columnName) throws Exception{
          float name = rs.getFloat(columnName);
          return(name);
       public boolean selectFruits() throws Exception{
          String query = "SELECT Id, Name FROM Fruit";
          stmt = conn.createStatement();
          rs = stmt.executeQuery(query);
          boolean ret = false;
          if (rs != null)
             ret = true;
          return(ret);
       public boolean selectMonths() throws Exception{
          String query = "SELECT Id, Name FROM Month";
          stmt = conn.createStatement();
          rs = stmt.executeQuery(query);
          boolean ret = false;
          if (rs != null)
             ret = true;
          return(ret);
       public boolean selectFruitForSale() throws Exception{
          String query = "SELECT F.Name AS Fruit, M.Name AS Month, Price, Weight, (Price * Weight) AS TotalPrice FROM FruitMonth AS FM, Fruit AS F, Month AS M WHERE FM.FruitId = F.Id AND FM.MonthId = M.Id ORDER BY M.Id";
          stmt = conn.createStatement();
          rs = stmt.executeQuery(query);
          boolean ret = false;
          if (rs != null)
             ret = true;
          return(ret);
       public int insertFruit(String name) throws Exception{
          String query = "INSERT INTO Fruit (Name) VALUES ('" + name + "')";
          stmt = conn.createStatement();
          int ret = stmt.executeUpdate(query);
          return(ret);
       public int insertFruitForSale(String insertValues) throws Exception{
          String query = "INSERT INTO FruitMonth (FruitId, MonthId, Price, Weight) VALUES (" + insertValues + ")";
          stmt = conn.createStatement();
          int ret = stmt.executeUpdate(query);
          return(ret);     
       public int deleteFruit(String fruitList) throws Exception{
          String query = "DELETE FROM Fruit WHERE Name IN (" + fruitList + ")";
          stmt = conn.createStatement();
          int ret = stmt.executeUpdate(query);
          return(ret);
       public void dbDisconnect() throws Exception{
          stmt.close();
          conn.close();
       public boolean checkFruitForSale(String thisfruit) throws Exception{
          String query = "SELECT F.Name AS Fruit, M.Name AS Month, Price, Weight, (Price * Weight) AS TotalPrice FROM FruitMonth AS FM, Fruit AS F, Month AS M WHERE FM.FruitId = F.Id AND FM.MonthId = M.Id AND F.Name IN (" + thisfruit + ") ORDER BY M.Id";
    try{
          stmt = conn.createStatement();
          rs = stmt.executeQuery(query);
    catch ( SQLException sqlException)
    sqlException.printStackTrace();
          boolean ret = false;
          if (rs != null)
             ret = true;
          return(ret);
    finally
    try{
    catch (Exception exception)
          boolean ret = false;
          if (rs != null)
             ret = true;
          return(ret);
       public String Check1(String columnName) throws Exception{
          String name = rs.getString(columnName);
          return(name);

    First thing to check would be the Tomcat log file. Most likely there is an error message printed there:
    Look in [TOMCAT]/logs for any files modified recently. Open it, and you should find some hints as to your error.
    It would be great if I could just see what is happening when
    FruitConnect is processing code.For that sort of thing, you want to use a logger. Either Log4J or the standard Java1.4 logger would help. Basically configure it to log statements to file as your program runs.
    I get no errors, just a blank screenThat could indicate that the page ran enough to fill up the page buffer, and then failed. When you view source, do you see anything on the page at all?

  • JSP + JDBC + MySql Problem (Tomcat 4.1)

    I'm completely helpless... whenever I try to retrieve stuff from the db (using a jsp page), I get errors that don't even make sense.
    out.println(stmt.executeQuery("SELECT * FROM newsTbl WHERE articleID = 1").getString("articleTitle"));if I try doing the above, I get a "ServletException : Before start of result set" error that supposedly occurred at this line of the generated servlet:
    if (pageContext != null) pageContext.handlePageException(t);---------------
    If i try this:
    ResultSet rsSec = stmt.executeQuery("SELECT * FROM newsSecTbl");
    rsSec.beforeFirst();  //<-- Even if I don't have this line the result does not change
      out.println(rsSec.next());
      while (rsSec.next()) { ... }I the while loop is never initiated, because rsSec.next() is false... kind of weird if you ask me, I even put two entries into the table to make sure the cursor wasnt at the first record and saying there was no second one (which would have been right if there were only one record).
    I would be very grateful if someone could help me out with this. I've never done any db programming with Java yet, so I dont have a clue what Im doing. By the way, I'm using MySql (indicated in the title) and the server was running and available when I ran the above code.
    Cheers,
    Tom

    You can't do this:
    out.println(stmt.executeQuery("SELECT * FROM newsTbl WHERE articleID = 1").getString("articleTitle"));The ResultSet you get back is a database cursor that doesn't point to the first row yet. The correct idiom is:
    String sql = "SELECT * FROM newsTbl WHERE articleID = 1";
    ResultSet result = stmt.executeQuery(sql);
    String articleTitle = "";
    while (result.next())
       title = result.getString("articleTitle");
    result.close();
    stmt.close();If you've never done DB programming before, I'd recommend that you click on the Tutorials link to the left and go through the JDBC tutorial carefully. You'll save yourself a lot of grief.
    Another good idea would be to separate out all your database code into at least one separate object, independent of the servlet. That way you can test and develop it off to the side until it's 100% solid. Then your servlet can simply instantiate one and use it. All your problems from that point forward will be servlet issues, because you'll know that your database code is working. - MOD
    See if that works better. - MOD

  • Problem in jdbc-tomcat-mysql connection

    hi everybody
    i m in serious problem since last 15-20 days. i m trying hard to make the connection jdbc-mysql using tomcat with the help of a jsp test page but every time i am facing almost the similar probems listed below in detail:
    to make sure that the jdrivers's .jar (mysql-connector-java-3.1.7-bin.jar) available for such connections working fine i have tried the above said connection without using tomcat....which is working fine...for this i have created a dummy database with a dummy table ..and written some queries in the .java file of my code which upon running inserts the specified values in the defined(dummy) database.
    this is the confirmation that the classpath etc..are ok in regard to the mysql-connector-java-3.1.7-bin.jar
    now i have placed a copy of this .jar file in to the commons/lib directory of the tomcat web server(which is suppossed to be the place for such external jars)
    after doing so i have followed 2 methods :
    method 1st:........
    i have made aone more jar file from the following .java file....
    import javax.naming.*;
    import javax.sql.*;
    import java.sql.*;
    public class TestSQLLoad
    String user = "Not Connected";
    String pwd = "no pwd";
    int id = -1;
    public void init() {
    try{
    Context ctx = new InitialContext();
    if(ctx == null ) {
    throw new Exception("Boom - No Context");
    DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/TestDB");
    if (ds != null) {
    Connection conn = ds.getConnection();
    if(conn != null) {
    user = "Got Connection "+conn.toString();
    Statement stmt = conn.createStatement();
    String q = "select name, password, id from user";
    ResultSet rst = stmt.executeQuery(q);
    if(rst.next()) {
    user=rst.getString(1);
    pwd=rst.getString(2);
    id = rst.getInt(3);
    conn.close();
    }catch(Exception e) {
    e.printStackTrace();
    public String getUser() {
    return user;
    public String getPassword() {
    return pwd;
    public int getID()
    return id;
    after compiling it at the cmd prompt i made a .jar file from the .class of it and named it MySQLLoad.jar...then i placed it also in to the commons/lib directory where the mysql-connector-java-3.1.7-bin.jar was already placed.
    then i have changed the server.xml and web.xml files from the conf directory of the tomcat as given here:
    server.xml
    <!-- Example Server Configuration File -->
    <!-- Note that component elements are nested corresponding to their
    parent-child relationships with each other -->
    <!-- A "Server" is a singleton element that represents the entire JVM,
    which may contain one or more "Service" instances. The Server
    listens for a shutdown command on the indicated port.
    Note: A "Server" is not itself a "Container", so you may not
    define subcomponents such as "Valves" or "Loggers" at this level.
    -->
    <Server port="8005" shutdown="SHUTDOWN">
    <!-- Comment these entries out to disable JMX MBeans support used for the
    administration web application -->
    <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />
    <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
    <!-- Global JNDI resources -->
    <GlobalNamingResources>
    <!-- Test entry for demonstration purposes -->
    <Environment name="simpleValue" type="java.lang.Integer" value="30"/>
    <!-- Editable user database that can also be used by
    UserDatabaseRealm to authenticate users -->
    <Resource name="UserDatabase" auth="Container"
    type="org.apache.catalina.UserDatabase"
    description="User database that can be updated and saved"
    factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
    pathname="conf/tomcat-users.xml" />
    </GlobalNamingResources>
    <!-- A "Service" is a collection of one or more "Connectors" that share
    a single "Container" (and therefore the web applications visible
    within that Container). Normally, that Container is an "Engine",
    but this is not required.
    Note: A "Service" is not itself a "Container", so you may not
    define subcomponents such as "Valves" or "Loggers" at this level.
    -->
    <!-- Define the Tomcat Stand-Alone Service -->
    <Service name="Catalina">
    <!-- A "Connector" represents an endpoint by which requests are received
    and responses are returned. Each Connector passes requests on to the
    associated "Container" (normally an Engine) for processing.
    By default, a non-SSL HTTP/1.1 Connector is established on port 8080.
    You can also enable an SSL HTTP/1.1 Connector on port 8443 by
    following the instructions below and uncommenting the second Connector
    entry. SSL support requires the following steps (see the SSL Config
    HOWTO in the Tomcat 5 documentation bundle for more detailed
    instructions):
    * If your JDK version 1.3 or prior, download and install JSSE 1.0.2 or
    later, and put the JAR files into "$JAVA_HOME/jre/lib/ext".
    * Execute:
    %JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA (Windows)
    $JAVA_HOME/bin/keytool -genkey -alias tomcat -keyalg RSA (Unix)
    with a password value of "changeit" for both the certificate and
    the keystore itself.
    By default, DNS lookups are enabled when a web application calls
    request.getRemoteHost(). This can have an adverse impact on
    performance, so you can disable it by setting the
    "enableLookups" attribute to "false". When DNS lookups are disabled,
    request.getRemoteHost() will return the String version of the
    IP address of the remote client.
    -->
    <!-- Define a non-SSL HTTP/1.1 Connector on port 8080 -->
    <Connector
    port="80" maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
    enableLookups="false" redirectPort="8443" acceptCount="100"
    connectionTimeout="20000" disableUploadTimeout="true" />
    <!-- Note : To disable connection timeouts, set connectionTimeout value
    to 0 -->
         <!-- Note : To use gzip compression you could set the following properties :
                   compression="on"
                   compressionMinSize="2048"
                   noCompressionUserAgents="gozilla, traviata"
                   compressableMimeType="text/html,text/xml"
         -->
    <!-- Define a SSL HTTP/1.1 Connector on port 8443 -->
    <!--
    <Connector port="8443"
    maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
    enableLookups="false" disableUploadTimeout="true"
    acceptCount="100" scheme="https" secure="true"
    clientAuth="false" sslProtocol="TLS" />
    -->
    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="8009"
    enableLookups="false" redirectPort="8443" protocol="AJP/1.3" />
    <!-- Define a Proxied HTTP/1.1 Connector on port 8082 -->
    <!-- See proxy documentation for more information about using this. -->
    <!--
    <Connector port="8082"
    maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
    enableLookups="false" acceptCount="100" connectionTimeout="20000"
    proxyPort="80" disableUploadTimeout="true" />
    -->
    <!-- An Engine represents the entry point (within Catalina) that processes
    every request. The Engine implementation for Tomcat stand alone
    analyzes the HTTP headers included with the request, and passes them
    on to the appropriate Host (virtual host). -->
    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Standalone" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <!-- Define the top level container in our container hierarchy -->
    <Engine name="Catalina" defaultHost="localhost">
    <!-- The request dumper valve dumps useful debugging information about
    the request headers and cookies that were received, and the response
    headers and cookies that were sent, for all requests received by
    this instance of Tomcat. If you care only about requests to a
    particular virtual host, or a particular application, nest this
    element inside the corresponding <Host> or <Context> entry instead.
    For a similar mechanism that is portable to all Servlet 2.4
    containers, check out the "RequestDumperFilter" Filter in the
    example application (the source for this filter may be found in
    "$CATALINA_HOME/webapps/examples/WEB-INF/classes/filters").
    Request dumping is disabled by default. Uncomment the following
    element to enable it. -->
    <!--
    <Valve className="org.apache.catalina.valves.RequestDumperValve"/>
    -->
    <!-- Because this Realm is here, an instance will be shared globally -->
    <!-- This Realm uses the UserDatabase configured in the global JNDI
    resources under the key "UserDatabase". Any edits
    that are performed against this UserDatabase are immediately
    available for use by the Realm. -->
    <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
    resourceName="UserDatabase"/>
    <!-- Comment out the old realm but leave here for now in case we
    need to go back quickly -->
    <!--
    <Realm className="org.apache.catalina.realm.MemoryRealm" />
    -->
    <!-- Replace the above Realm with one of the following to get a Realm
    stored in a database and accessed via JDBC -->
    <!--
    <Realm className="org.apache.catalina.realm.JDBCRealm"
    driverName="org.gjt.mm.mysql.Driver"
    connectionURL="jdbc:mysql://localhost/authority"
    connectionName="test" connectionPassword="test"
    userTable="users" userNameCol="user_name" userCredCol="user_pass"
    userRoleTable="user_roles" roleNameCol="role_name" />
    -->
    <!--
    <Realm className="org.apache.catalina.realm.JDBCRealm"
    driverName="oracle.jdbc.driver.OracleDriver"
    connectionURL="jdbc:oracle:thin:@ntserver:1521:ORCL"
    connectionName="scott" connectionPassword="tiger"
    userTable="users" userNameCol="user_name" userCredCol="user_pass"
    userRoleTable="user_roles" roleNameCol="role_name" />
    -->
    <!--
    <Realm className="org.apache.catalina.realm.JDBCRealm"
    driverName="sun.jdbc.odbc.JdbcOdbcDriver"
    connectionURL="jdbc:odbc:CATALINA"
    userTable="users" userNameCol="user_name" userCredCol="user_pass"
    userRoleTable="user_roles" roleNameCol="role_name" />
    -->
    <!-- Define the default virtual host
    Note: XML Schema validation will not work with Xerces 2.2.
    -->
    <Host name="localhost" appBase="webapps"
    unpackWARs="true" autoDeploy="true"
    xmlValidation="false" xmlNamespaceAware="false">
    <!-- Defines a cluster for this node,
    By defining this element, means that every manager will be changed.
    So when running a cluster, only make sure that you have webapps in there
    that need to be clustered and remove the other ones.
    A cluster has the following parameters:
    className = the fully qualified name of the cluster class
    name = a descriptive name for your cluster, can be anything
    mcastAddr = the multicast address, has to be the same for all the nodes
    mcastPort = the multicast port, has to be the same for all the nodes
    mcastBindAddr = bind the multicast socket to a specific address
    mcastTTL = the multicast TTL if you want to limit your broadcast
    mcastSoTimeout = the multicast readtimeout
    mcastFrequency = the number of milliseconds in between sending a "I'm alive" heartbeat
    mcastDropTime = the number a milliseconds before a node is considered "dead" if no heartbeat is received
    tcpThreadCount = the number of threads to handle incoming replication requests, optimal would be the same amount of threads as nodes
    tcpListenAddress = the listen address (bind address) for TCP cluster request on this host,
    in case of multiple ethernet cards.
    auto means that address becomes
    InetAddress.getLocalHost().getHostAddress()
    tcpListenPort = the tcp listen port
    tcpSelectorTimeout = the timeout (ms) for the Selector.select() method in case the OS
    has a wakup bug in java.nio. Set to 0 for no timeout
    printToScreen = true means that managers will also print to std.out
    expireSessionsOnShutdown = true means that
    useDirtyFlag = true means that we only replicate a session after setAttribute,removeAttribute has been called.
    false means to replicate the session after each request.
    false means that replication would work for the following piece of code: (only for SimpleTcpReplicationManager)
    <%
    HashMap map = (HashMap)session.getAttribute("map");
    map.put("key","value");
    %>
    replicationMode = can be either 'pooled', 'synchronous' or 'asynchronous'.
    * Pooled means that the replication happens using several sockets in a synchronous way. Ie, the data gets replicated, then the request return. This is the same as the 'synchronous' setting except it uses a pool of sockets, hence it is multithreaded. This is the fastest and safest configuration. To use this, also increase the nr of tcp threads that you have dealing with replication.
    * Synchronous means that the thread that executes the request, is also the
    thread the replicates the data to the other nodes, and will not return until all
    nodes have received the information.
    * Asynchronous means that there is a specific 'sender' thread for each cluster node,
    so the request thread will queue the replication request into a "smart" queue,
    and then return to the client.
    The "smart" queue is a queue where when a session is added to the queue, and the same session
    already exists in the queue from a previous request, that session will be replaced
    in the queue instead of replicating two requests. This almost never happens, unless there is a
    large network delay.
    -->
    <!--
    When configuring for clustering, you also add in a valve to catch all the requests
    coming in, at the end of the request, the session may or may not be replicated.
    A session is replicated if and only if all the conditions are met:
    1. useDirtyFlag is true or setAttribute or removeAttribute has been called AND
    2. a session exists (has been created)
    3. the request is not trapped by the "filter" attribute
    The filter attribute is to filter out requests that could not modify the session,
    hence we don't replicate the session after the end of this request.
    The filter is negative, ie, anything you put in the filter, you mean to filter out,
    ie, no replication will be done on requests that match one of the filters.
    The filter attribute is delimited by ;, so you can't escape out ; even if you wanted to.
    filter=".*\.gif;.*\.js;" means that we will not replicate the session after requests with the URI
    ending with .gif and .js are intercepted.
    The deployer element can be used to deploy apps cluster wide.
    Currently the deployment only deploys/undeploys to working members in the cluster
    so no WARs are copied upons startup of a broken node.
    The deployer watches a directory (watchDir) for WAR files when watchEnabled="true"
    When a new war file is added the war gets deployed to the local instance,
    and then deployed to the other instances in the cluster.
    When a war file is deleted from the watchDir the war is undeployed locally
    and cluster wide
    -->
    <!--
    <Cluster className="org.apache.catalina.cluster.tcp.SimpleTcpCluster"
    managerClassName="org.apache.catalina.cluster.session.DeltaManager"
    expireSessionsOnShutdown="false"
    useDirtyFlag="true"
    notifyListenersOnReplication="true">
    <Membership
    className="org.apache.catalina.cluster.mcast.McastService"
    mcastAddr="228.0.0.4"
    mcastPort="45564"
    mcastFrequency="500"
    mcastDropTime="3000"/>
    <Receiver
    className="org.apache.catalina.cluster.tcp.ReplicationListener"
    tcpListenAddress="auto"
    tcpListenPort="4001"
    tcpSelectorTimeout="100"
    tcpThreadCount="6"/>
    <Sender
    className="org.apache.catalina.cluster.tcp.ReplicationTransmitter"
    replicationMode="pooled"
    ackTimeout="15000"/>
    <Valve className="org.apache.catalina.cluster.tcp.ReplicationValve"
    filter=".*\.gif;.*\.js;.*\.jpg;.*\.htm;.*\.html;.*\.txt;"/>
    <Deployer className="org.apache.catalina.cluster.deploy.FarmWarDeployer"
    tempDir="/tmp/war-temp/"
    deployDir="/tmp/war-deploy/"
    watchDir="/tmp/war-listen/"
    watchEnabled="false"/>
    </Cluster>
    -->
    <!-- Normally, users must authenticate themselves to each web app
    individually. Uncomment the following entry if you would like
    a user to be authenticated the first time they encounter a
    resource protected by a security constraint, and then have that
    user identity maintained across all web applications contained
    in this virtual host. -->
    <!--
    <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
    -->
    <!-- Access log processes all requests for this virtual host. By
    default, log files are created in the "logs" directory relative to
    $CATALINA_HOME. If you wish, you can specify a different
    directory with the "directory" attribute. Specify either a relative
    (to $CATALINA_HOME) or absolute path to the desired directory.
    -->
    <!--
    <Valve className="org.apache.catalina.valves.AccessLogValve"
    directory="logs" prefix="localhost_access_log." suffix=".txt"
    pattern="common" resolveHosts="false"/>
    -->
    <!-- Access log processes all requests for this virtual host. By
    default, log files are created in the "logs" directory relative to
    $CATALINA_HOME. If you wish, you can specify a different
    directory with the "directory" attribute. Specify either a relative
    (to $CATALINA_HOME) or absolute path to the desired directory.
    This access log implementation is optimized for maximum performance,
    but is hardcoded to support only the "common" and "combined" patterns.
    -->
    <!--
    <Valve className="org.apache.catalina.valves.FastCommonAccessLogValve"
    directory="logs" prefix="localhost_access_log." suffix=".txt"
    pattern="common" resolveHosts="false"/>
    -->
    <Context path="/testdb" docBase="TOMCAT_HOME/webapps/tomcat-docs/testdb"
    debug="5" reloadable="true" crossContext="true" >
    <Logger className="org.apache.catalina.logger.FileLogger"
    prefix="localhost_DBTest_log." suffix=".txt"
    timestamp="true"/>
    <Resource name="jdbc/TestDB"
    auth="Container"
    type="javax.sql.DataSource"/>
    <ResourceParams name="jdbc/TestDB">
    <parameter>
    <name>factory</name>
    <value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
    </parameter>
    <!-- Maximum number of dB connections in pool. Make sure you
    configure your mysqld max_connections large enough to handle
    all of your db connections. Set to 0 for no limit.
    -->
    <parameter>
    <name>maxActive</name>
    <value>10</value>
    </parameter>
    <!-- Maximum number of idle dB connections to retain in pool.
    Set to 0 for no limit.
    -->
    <parameter>
    <name>maxIdle</name>
    <value>5</value>
    </parameter>
    <!-- Maximum time to wait for a dB connection to become available
    in ms, in this example 10 seconds. An Exception is thrown if
    this timeout is exceeded. Set to -1 to wait indefinitely.
    -->
    <parameter>
    <name>maxWait</name>
    <value>10000</value>
    </parameter>
    <!-- MySQL dB username and password for dB connections -->
    <parameter>
    <name>username</name>
    <value>root</value>
    </parameter>
    <parameter>
    <name>password</name>
    <value>mysql</value>
    </parameter>
    <!-- Class name for mm.mysql JDBC driver -->
    <parameter>
    <name>driverClassName</name>
    <value>com.mysql.jdbc.Driver</value>
    </parameter>
    <!-- The JDBC connection url for connecting to your MySQL dB.
    The autoReconnect=true argument to the url makes sure that the
    mm.mysql JDBC Driver will automatically reconnect if mysqld closed the
    connection. mysqld by default closes idle connections after 8 hours.
    -->
    <parameter>
    <name>url</name>
    <value>jdbc:mysql://localhost/testdb?autoReconnect=true</value>
    </parameter>
    </ResourceParams>
    </Context>
    </Host>
    </Engine>
    </Service>
    </Server>
    and the other xml file i.e
    web.xml is here:
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
    <!-- ======================== Introduction ============================== -->
    <!-- This document defines default values for all web applications -->
    <!-- loaded into this instance of Tomcat. As each application is -->
    <!-- deployed, this file is processed, followed by the -->
    <!-- "/WEB-INF/web.xml" deployment descriptor from your own -->
    <!-- applications. -->
    <!-- -->
    <!-- WARNING: Do not configure application-specific resources here! -->
    <!-- They should go in the "/WEB-INF/web.xml" file in your application. -->
    <!-- ================== Built In Servlet Definitions ==================== -->
    <!-- The default servlet for all web applications, that serves static -->
    <!-- resources. It processes all requests that are not mapped to other -->
    <!-- servlets with servlet mappings (defined either here or in your own -->
    <!-- web.xml file. This servlet supports the following initialization -->
    <!-- parameters (default values are in square brackets): -->
    <!-- -->
    <!-- debug Debugging detail level for messages logged -->
    <!-- by this servlet. [0] -->
    <!-- -->
    <!-- input Input buffer size (in bytes) when reading -->
    <!-- resources to be served. [2048] -->
    <!-- -->
    <!-- listings Should directory listings be produced if there -->
    <!-- is no welcome file in this directory? [true] -->
    <!-- -->
    <!-- output Output buffer size (in bytes) when writing -->
    <!-- resources to be served. [2048] -->
    <!-- -->
    <!-- readonly Is this context "read only", so HTTP -->
    <!-- commands like PUT and DELETE are -->
    <!-- rejected? [true] -->
    <!-- -->
    <!-- readmeFile File name to display with the directory -->
    <!-- contents. [null] -->
    <!-- -->
    <!-- For directory listing customization. Checks localXsltFile, then -->
    <!-- globalXsltFile, then defaults to original behavior. -->
    <!-- -->
    <!-- localXsltFile Make directory listings an XML doc and -->
    <!-- pass the result to this style sheet residing -->
    <!-- in that directory. This overrides -->
    <!-- globalXsltFile[null] -->
    <!-- -->
    <!-- globalXsltFile Site wide configuration version of -->
    <!-- localXsltFile This argument is expected -->
    <!-- to be a physical file. [null] -->
    <!-- -->
    <!-- -->
    <servlet>
    <servlet-name>default</servlet-name>
    <resource-ref>
    <description>DB Connection</description>
    <res-ref-name>jdbc/TestDB</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    </resource-ref>
    <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
    <init-param>
    <param-name>debug</param-name>
    <param-value>0</param-value>
    </init-param>
    <init-param>
    <param-name>listings</param-name>
    <param-value>true</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    </servlet>
    <!-- The "invoker" servlet, which executes anonymous servlet classes -->
    <!-- that have not been defined in a web.xml file. Traditionally, this -->
    <!-- servlet is mapped to the URL pattern "/servlet/*", but you can map -->
    <!-- it to other patterns as well. The extra path info portion of such a -->
    <!-- request must be the fully qualified class name of a Java class that -->
    <!-- implements Servlet (or extends HttpServlet), or the servlet name -->
    <!-- of an existing servlet definition. This servlet supports the -->
    <!-- following initialization parameters (default values are in square -->
    <!-- brackets): -->
    <!-- -->
    <!-- debug Debugging detail level for messages logged -->
    <!-- by this servlet. [0] -->
    <servlet>
    <servlet-name>invoker</servlet-name>
    <servlet-class>
    org.apache.catalina.servlets.InvokerServlet
    </servlet-class>
    <init-param>
    <param-name>debug</param-name>
    <param-value>0</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
    </servlet>
    <!-- The JSP page compiler and execution servlet, which is the mechanism -->
    <!-- used by Tomcat to support JSP pages. Traditionally, this servlet -->
    <!-- is mapped to the URL pattern "*.jsp". This servlet supports the -->
    <!-- following initialization parameters (default values are in square -->
    <!-- brackets): -->
    <!-- -->
    <!-- checkInterval If development is false and checkInterval is -->
    <!-- greater than zero, background compilations are -->
    <!-- enabled. checkInterval is the time in seconds -->
    <!-- between checks to see if a JSP page needs to -->
    <!--

    Look at the URl below:
    How to connect to Microsoft SQL server with Type 4 JDBC driver
    http://www.java-tips.org/content/view/615/29/

  • JSP with MYSQL.

    Dear Friends
    I have a unique problem in java, when i try to connect to mysql db.
    It shows an error message:
    Unable to load driver. Getting Connection ... SQLException: No suitable driverI am using mysql MySQL 4.1.9 and tomcat 5.5 version.
    though i have loaded the driver in lib directory, it still displays the same error
    messgae. Here is the jsp file which i use to connect to my database.
    http://localhost:8080/mysqljdbc.jsp
    <%@ page import="java.net.*" %>
    <%@ page import="java.util.*" %>
    <%@ page import="java.io.*" %>
    <%@ page import="java.sql.*" %>
    <%
         try{
         Class.forName("com.mysql.jdbc.Driver").newInstance();
         catch (Exception E) {
         out.println("Unable to load driver.");
         E.printStackTrace();
         try{
              out.println("Getting Connection ...");
              Connection C = DriverManager.getConnection("jdbc:mysql://localhost:3306/vinoth");
              out.println("<br>Connected:  " + !C.isClosed() + "<br>\n");
              out.println("Catalog:  " + C.getCatalog() + "<br>\n");
                   Statement S = C.createStatement();
                   ResultSet rs = S.executeQuery("SELECT * FROM foo");
                   ResultSetMetaData rsStruc = rs.getMetaData();
                   out.println("Table:  " + rsStruc.getTableName(1) + "<br>");
                   out.println("<table bgcolor=c8c8c8 cellpadding=5 cellspacing=1>");
                   out.println("<tr bgcolor=000000>");
                   int colCount = rsStruc.getColumnCount();
                   String colName = "";
                   for(int i=1;i <= colCount; i++){
                   colName = rsStruc.getColumnName(i) ;
                   out.println("<td><B><font color=white>" + colName + "</font></b></td>\n");
                   out.println("</tr>");
                   while (rs.next()) {
                   out.println("<tr bgcolor=ffffff>");
                   for(int i=1;i <= colCount; i++){
                   colName = rsStruc.getColumnName(i) ;
                   String fld = rs.getString(colName);
                        out.println("<td>" + fld + "</td>");
                   out.println("</tr>");
                   out.println("</table>");
                   rs.close();
                   C.close();
         catch (Exception E) {
          out.println("SQLException: " + E.getMessage());
    %>Now is there anything i have to configure apart from this.
    Thanx in advance.

    First things first...i definitely recommend you take out the db stuff out of the jsp page. Place the logic in a DAO and if you have to reference the dao in the jsp. Although in a practice you should have a service layer which does the db stuff. Use a servlet to call the service layer and pass the results of the service layer to the jsp.
    Writing java code like that in the jsp is just bad programming. There are loads of web frameworks that enable you to develop scalable web applications.
    I realise that this does not help you but it is a good idea to get the design correct before embarking on the development.

  • First JSP/Tomcat 5.5 test

    Hi,
    I'm new in Java and i'm trying to create a web application in JSP.
    Basically, it should connect to a MS access database for the first steps, after it should use a MySQL DB.
    In this purpose i would like to build this web application as flexible as it is, because i don't want to recompile or rebuild code from migration Access to MySQL.
    1. where can i find a good tutorial about tomcat 5.5 setup ? I have a book for now, but it's very long way to first test...i just cover 10 % in 2 days. :(
    2. where can i find a very good tutorial about connect MS access DB from JSP ?
    3. how to it as flexible as i want ?
    thx,
    Maileen

    1. where can i find a good tutorial about tomcat 5.5
    setup ? I have a book for now, but it's very long way
    to first test...i just cover 10 % in 2 days. :(http://www.coreservlets.com/Apache-Tomcat-Tutorial/
    http://jakarta.apache.org/tomcat/tomcat-5.5-doc/index.html
    2. where can i find a very good tutorial about
    connect MS access DB from JSP ?you mean JDBC http://java.sun.com/j2se/1.5.0/docs/guide/jdbc/index.html
    3. how to it as flexible as i want ?you can save the connection string and the jdbc driver class name and the username and password to a file and then you application should read this data from that file. when you need to move form access to mysql just change the data in the file

  • Tomcat - MySQL - Cannot create resource instance

    I keep getting an error when trying to lookup my JNDI name. I know that this name is bound to a Context because I can list the bindings
    Context initCtx = new InitialContext();
    NamingEnumeration enum = initCtx.listBindings("java:comp/env/jdbc");
    while (enum.hasMoreElements()) {
    System.out.println(enum.nextElement().toString());
    And sure enough the name of my database I added through the console appears. However, I keep getting this error:
    javax.naming.NamingException: Cannot create resource instance
    on this second line of code
    Context ctx = new InitialContext();
    DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/ArgonautDB");
    My MySQL Connector jar file is in $CATALINA_HOME/common/lib and I believe my server.xml settings are correct because I added this Data Source to the context through the console and the web.xml file should be simple...nevertheless I still get this error.
    Any suggestions on where I else I can turn. Pulling my precious few last hairs out here....

    Thank you very much. That did the trick. Actually what did the trick was to reinstall tomcat with the standard installation, NOT the LE installation which doesn't include the dbcp jar files needed for connecting to a database - but you were right about missing those.
    I was dissapointed in Tomcat's documentation of this issue. I would have thought that something that has to have caused other developers problems like this would have been documented somewhere more pronounced (if at all) on Tomcat's site.
    For those other newbies out there who don't want to pull out your hair...here is a summary of the steps I took to remedy this problem.
    1) Install the latest version of Tomcat. Do NOT install the LE version, it does not include the neccessary library files to connect to a database (commons-dbcp.jar and commons-pool.jar).
    2) Download the latest mysql connector library from http://www.mysql.com/downloads/mysqlcc.html. Once you have extracted the tar file, there will be some directories, a README file, a couple other text files and a jar file named mysql-connector-java-VERSION-stable-bin.jar. Move the mysql-connector-java-VERSION-stable-bin.jar file to $CATALINA_HOME/common/lib.
    3) Follow the instructions on http://jakarta.apache.org/tomcat/tomcat-4.1-doc/jndi-datasource-examples-howto.html
    to create a test database, a test jsp file and a test class to access the database.

  • Problems with JSP and MySql bean.

    Hi,
    I'm new to JSP and I'm having some problems with it. I'm trying to do a simple login where a java class (bean?) handles the SQL injektion. I have deployed the page on tomcat and it works fine, except that the sqlinjektion does basically nothing. I have installed the mysql driver. I think there is something wrong with the java class, or the way im calling it. It does not produce any error. But its like it would never actually process the java code, because ive tried to append things to error string to see what is going on, nothing happens. everything stay null, no exceptions are thrown. If I implement the code to JSP itself, it does load the driver and print exception that there is no connection to database (which is correct). What am I missing? Code follows:
    the sqlhandler:
    public abstract class SqlInjektor {
         private static String Database = "*****";
         private static String serverName = "localhost:3306";
         private static String usrName="******";
         private static String passw="******";
         * @return Connection
         public static Connection createConnection(String error){
              Connection mySqlCon = null;
              try{
                   Class.forName("com.mysql.jdbc.Driver").newInstance();
              catch(Exception E){
                   PrintWriter out = response.getWriter();
                   out.println("lol");
              String url = "jdbc:mysql://" + serverName + "/" + Database + "?user=" + usrName + "&password=" + passw;
              try{
                   mySqlCon = DriverManager.getConnection(url);
              catch (Exception E){
                   E.printStackTrace(System.out);
              return mySqlCon;
         * Metodi saa sy�tteen��n SQL komennon, jonka se suorittaa sek� palauttaa komennon tulokset.
         * @param command
         * @return ResultSet
         public static ResultSet querySQL(String command,String error, Connection con){
              ResultSet rs = null;
              try{
                   Statement stmt = con.createStatement();
                   rs = stmt.executeQuery(command);
              catch(Exception E){
                   E.printStackTrace(System.out);
              return rs;
    the jsp page:
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ page isErrorPage="false" %>
    <%@ page import="java.sql.*" %>
    <%@page import="ot3.User"%>
    <%@page import="ot3.SqlInjektor"%>
    <%@page import="Javax.servlet.jsp.*"%>
    <!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>vastaanotto</title>
    </head>
    <body>
    <%!      String id;
         String password;
         String error = new String("Error!\n");
         User user;
    %>
    <%      user = new User();
         session.putValue("currentUser",user);
         id = request.getParameter("authName");
    password = request.getParameter("Password");
         Connection conn=null;
         ResultSet rs=null;
         conn = SqlInjektor.createConnection(error);
         if(conn!=null){
              out.println("conn ok!");
              rs = SqlInjektor.querySQL("SELECT * FROM user WHERE id='" + id +"' AND password='" + password+"' COLLATE latin1_bin;",error,conn);}
         try {
              if (rs!= null && rs.next()){
                   user.setID(rs.getInt("id"));
                   user.setName(rs.getString("name"));
                   user.setPassword(rs.getString("password"));
                   user.setClearance(rs.getInt("clearance"));
                   if(rs.getString("addedby")!=null)
                        user.setAdder(rs.getInt("addedby"));
                   if(rs.getString("lastmodifier")!=null)
                        user.setModifier(rs.getInt("lastmodifier"));
                   rs.close();%>
                   ONNISTU!
              <%}
              else {
                   out.println(error);     
         } catch (SQLException e) {
              out.println(e.getMessage());
         }%>
    </body>
    </html>

    Hi,
    I'm new to JSP and I'm having some problems with it. I'm trying to do a simple login where a java class (bean?) handles the SQL injektion. I have deployed the page on tomcat and it works fine, except that the sqlinjektion does basically nothing. I have installed the mysql driver. I think there is something wrong with the java class, or the way im calling it. It does not produce any error. But its like it would never actually process the java code, because ive tried to append things to error string to see what is going on, nothing happens. everything stay null, no exceptions are thrown. If I implement the code to JSP itself, it does load the driver and print exception that there is no connection to database (which is correct). What am I missing? Code follows:
    the sqlhandler:
    public abstract class SqlInjektor {
         private static String Database = "*****";
         private static String serverName = "localhost:3306";
         private static String usrName="******";
         private static String passw="******";
         * @return Connection
         public static Connection createConnection(String error){
              Connection mySqlCon = null;
              try{
                   Class.forName("com.mysql.jdbc.Driver").newInstance();
              catch(Exception E){
                   PrintWriter out = response.getWriter();
                   out.println("lol");
              String url = "jdbc:mysql://" + serverName + "/" + Database + "?user=" + usrName + "&password=" + passw;
              try{
                   mySqlCon = DriverManager.getConnection(url);
              catch (Exception E){
                   E.printStackTrace(System.out);
              return mySqlCon;
         * Metodi saa sy�tteen��n SQL komennon, jonka se suorittaa sek� palauttaa komennon tulokset.
         * @param command
         * @return ResultSet
         public static ResultSet querySQL(String command,String error, Connection con){
              ResultSet rs = null;
              try{
                   Statement stmt = con.createStatement();
                   rs = stmt.executeQuery(command);
              catch(Exception E){
                   E.printStackTrace(System.out);
              return rs;
    the jsp page:
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ page isErrorPage="false" %>
    <%@ page import="java.sql.*" %>
    <%@page import="ot3.User"%>
    <%@page import="ot3.SqlInjektor"%>
    <%@page import="Javax.servlet.jsp.*"%>
    <!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>vastaanotto</title>
    </head>
    <body>
    <%!      String id;
         String password;
         String error = new String("Error!\n");
         User user;
    %>
    <%      user = new User();
         session.putValue("currentUser",user);
         id = request.getParameter("authName");
    password = request.getParameter("Password");
         Connection conn=null;
         ResultSet rs=null;
         conn = SqlInjektor.createConnection(error);
         if(conn!=null){
              out.println("conn ok!");
              rs = SqlInjektor.querySQL("SELECT * FROM user WHERE id='" + id +"' AND password='" + password+"' COLLATE latin1_bin;",error,conn);}
         try {
              if (rs!= null && rs.next()){
                   user.setID(rs.getInt("id"));
                   user.setName(rs.getString("name"));
                   user.setPassword(rs.getString("password"));
                   user.setClearance(rs.getInt("clearance"));
                   if(rs.getString("addedby")!=null)
                        user.setAdder(rs.getInt("addedby"));
                   if(rs.getString("lastmodifier")!=null)
                        user.setModifier(rs.getInt("lastmodifier"));
                   rs.close();%>
                   ONNISTU!
              <%}
              else {
                   out.println(error);     
         } catch (SQLException e) {
              out.println(e.getMessage());
         }%>
    </body>
    </html>

Maybe you are looking for

  • Beginners guide to integrating Flash Media Server 2?

    I'm a newbit to Flasha dn flash media server and need some help with integrating the two products. We've just purchased Flash Media Server 2 to stream user created videos to a website. Idealy we would like to use the FlvPlayBack component placed on t

  • Editing issue with DVCpro 50, blak lines right and left

    Hello to everyone, I am editing in native DVCpro 50. In the canvas I get a thin black line left and right, so the footgae is not completely covering the canvas view. Should I resize the footgae a little bit to match this? My problem is that I am brin

  • Vendor Evaluation in SRM5.0

    Hi Team, Please provide me a Config Document to set up Vendor Evaluation in SRM 5.0. We are using Classic Scenario.Please also provide any useful tip for the same. Thanks Anita

  • I need your help and opinion on JNI

    I am assigned a task to build one Java API above one existing protocol stack written in legacy C++, which involves UDP and TCP communication. The C++ code involves callback method. My qustion is: 1. I only tried some simple examples on one way trasfe

  • How to get alert that a vm is up?

    hi guys, how to get alert when tenant vm is getting up?