JSP & JDBC

Hi. I have researched JSP, but would like to learn how to use JDBC. I am currently trying to create a forum, but need a basic tutorial of how to connect the two together. A simple, very basic website will do, and it would be great if I could see primitive sample codes of using JSP to access and manipulate a database.
Best regards,
Ben.

Hello
I would suguest you not connect to database from JSP but instead use Bean for this job. It's more right thing to do , and leave JSP as less code as posible.
Here is exemple code that i made for myself (connecting to MySql)
*  Class for SqlBase query to get the menu from Mysql database
*      EXEMPLE OF CONNECTING TO MYSQL WITH JDBC BY QUERY
*            Connection conn = null;
*            Class.forName("com.mysql.jdbc.Driver").newInstance();
*            conn = DriverManager.getConnection(connStr);
*            Statement s = conn.createStatement();
*            String query = "Select menu_id, menu_name, menu_link from blog_menu";
*            ResultSet resultset = s.executeQuery(query);
*      EXEMPLE OF CONNECTING TO MYSQL WITH JDBC BY USING STORED PROCEDURES
*           Connection conn = null;
*           Class.forName("com.mysql.jdbc.Driver").newInstance();
*           conn = DriverManager.getConnection(connStr);
*           CallableStatement cStmt = conn.prepareCall("{call sp_BlogMenu()}");
*           cStmt.execute();
*           ResultSet resultset = cStmt.getResultSet(); 
*                      OR INSTEAD OF TWO LAST LINES IT'S CAN BE DONE
*          ResultSet resultset =  cStmt.executeQuery();
*      CLOSING CONNECTION
*          if( conn != null )
*               conn.close();
*               s.close();
*               cStmt.close();
*               resultset.close();
*/Hope it helps.

Similar Messages

  • Cannot access VARCHAR2s on Oracle 9i using JSP/JDBC

    After upgrading from Oracle 8.1.7 to Oracle 9, I get an
    exception when using JSP/JDBC to read data from columns
    containing VARCHAR2s. I can successfully read columns
    containing BLOBs, CLOBs, NUMBERs, and RAWs.
    I still can select VARCHAR2 columns by using SQL*Plus so the
    problem is with JDBC and not the database.
    I get the following exception message:
    java.sql.SQLException: ORA-00600: internal error code,
    arguments: [ttcgcshnd-1], [0], [], [], [], [], [], []
    The following code that worked on Oracle 8 fails to execute
    properly on Oracle 9:
    OracleResultSet rs = null;
    String sql = "select name from users where id > 100";
    rs = (OracleResultSet)s.executeQuery(sql);
    I'm using Windows 2000, Tomcat 3.2.2, Java 1.3, and the latest
    version of OracleJSP.
    Has anyone run into this problem?
    I've also entered this same query on the Java-SQLJ/JDBC
    discussion fourm.

    I4ve installed Oracle 9i on RedHat 7.2.
    We develop with WebObjects and JBuilder.
    When i try to connect to the database via the EOModeller (JDBC) i got the same error:
    Stack Trace:
    JDBCAdaptorException: ORA-00600: Interner Fehlercode, Argumente: [ttcgcshnd-1], [0], [], [], [], [], [], []
    Then, i started creating and droping tables in the 9i Database >> it works fine.
    Can someone give an solution for this problem??

  • Servlet/jsp/jdbc best approach

    Hello guys
    Which is the best approach when developing servlet/jsp/jdbc? I will take an
    example:
    I have index-page, page2 and page 3.
    When the user writes www.mydomain.com then the page index.jsp checks if the
    user is coming from the servlet, like this:
    <%
    if(request.getAttribute("getPageTitle")==null){
    %>
    <jsp:forward page="/Index" />
    <%
    else{
    %>
    <%@ include file="/include/header.jsp" %>
    content for index.jsp
    <%@ include file="/include/footer.jsp" %>
    <%
    %>
    On the other hand, the Index class has this init()
    public void init(ServletConfig config) throws ServletException {
    super.init(config);
    con = DatabaseConf.getConnection();
    DatabaseConf is a class that handles all the operations related to the
    database.
    Index.class has also the doGet-method like this:
    request.setAttribute ("getPageTitle", "AnyTilte");
    getServletConfig().getServletContext().getRequestDispatcher("/index.jsp").forward(request,
    response);
    Does it looks ok so long?
    Now, I have other pages, page2 and page3 (in fact I have mych more than just
    these, but this is only an example)
    pages.jsp works as index.jsp. It makes a check
    <%
    if(request.getAttribute("getPageTitle")==null){
    %>
    if not satisfied than it redirect to
    <jsp:forward page="/Page2" />
    My concern, however, is about databasemanagement. Even the Page.class has an
    init-method that looks exactly like the one in Index.class, e.g.
    public void init(ServletConfig config) throws ServletException {
    super.init(config);
    con = DatabaseConf.getConnection();
    In conclusion, Im starting jdbc-connection for every class-file that
    initiates. Is this a good approach? What I would like is a solution to
    initiate the database only one time, when the server starts. Not everytime,
    the first time a specially class-file will be called. I know, this will
    happens only one time for a file for the server's lifetime. But Im afraid
    this is not a good way to work.
    Regards
    email2us

    Hello guys
    Which is the best approach when developing
    servlet/jsp/jdbc? I will take an
    example:
    I have index-page, page2 and page 3.
    When the user writes www.mydomain.com then the page
    index.jsp checks if the
    user is coming from the servlet, like this:
    <%
    if(request.getAttribute("getPageTitle")==null){
    %>
    <jsp:forward page="/Index" />
    <%
    else{
    %>
    <%@ include file="/include/header.jsp" %>
    content for index.jsp
    <%@ include file="/include/footer.jsp" %>
    <%
    %>
    On the other hand, the Index class has this init()
    public void init(ServletConfig config) throws
    ServletException {
    super.init(config);
    con = DatabaseConf.getConnection();
    DatabaseConf is a class that handles all the
    operations related to the
    database.
    Index.class has also the doGet-method like this:
    request.setAttribute ("getPageTitle", "AnyTilte");
    getServletConfig().getServletContext().getRequestDispa
    tcher("/index.jsp").forward(request,
    response);
    Does it looks ok so long?
    Now, I have other pages, page2 and page3 (in fact I
    have mych more than just
    these, but this is only an example)
    pages.jsp works as index.jsp. It makes a check
    <%
    if(request.getAttribute("getPageTitle")==null){
    %>
    if not satisfied than it redirect to
    <jsp:forward page="/Page2" />
    My concern, however, is about databasemanagement.
    Even the Page.class has an
    init-method that looks exactly like the one in
    Index.class, e.g.
    public void init(ServletConfig config) throws
    ServletException {
    super.init(config);
    con = DatabaseConf.getConnection();
    Please use the code formatting tags when posting actual code.
    In conclusion, Im starting jdbc-connection for every
    class-file that
    initiates. Is this a good approach? You normally do not want your Servlet to initiate (which I take to mean 'startup') a database. The two can run independently. The place to initiate a database is in your operating system's startup scripts.
    What I would like
    is a solution to
    initiate the database only one time, when the server
    starts. Not everytime,
    the first time a specially class-file will be called.If you are talking about java.sql.Connection, you generally do not want to have a single connection for your entire application. Each thread should use its own connection, or transaction management/logical unit of work will be problematic, at best. You can use a connection pool to improve performance. However, from a caller's perspective, they are receiving a new connection each time.
    I know, this will
    happens only one time for a file for the server's
    lifetime. But Im afraid
    this is not a good way to work.
    Regards
    email2us- Saish

  • 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

  • Jsp jdbc connectivity problem.

    i'm getting the following error
    "HTTP Status 500-----
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    org.apache.jasper.JasperException: /create_user.jsp(2,4) Invalid directive
    org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:40)
    org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:407)
    org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:88)
    org.apache.jasper.compiler.Parser.parseDirective(Parser.java:527)
    org.apache.jasper.compiler.Parser.parseElements(Parser.java:1568)
    org.apache.jasper.compiler.Parser.parse(Parser.java:132)
    org.apache.jasper.compiler.ParserController.doParse(ParserController.java:212)
    org.apache.jasper.compiler.ParserController.parse(ParserController.java:101)
    org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:156)"
    for the jsp file is :
    <%@ page import="java.sql.*" %>
    <%@ //page errorPage="exceptionHandler.jsp"%>
    <%
    String connectionURL = "jdbc:mysql://localhost:3306/decipher?user=localhost;password=passwd";
    Connection connection = null;
    Statement statement = null;
    ResultSet rs = null;
    %>
    <html><body>
    <%
    String nr="nr";
    String a= request.getParameter("emp_id");
    String b= request.getParameter("name");
    String c= request.getParameter("department");
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    connection = DriverManager.getConnection(connectionURL, "root", "passwd");
    statement = connection.createStatement();
    statement.executeUpdate("use decipher");
    statement.executeUpdate("Insert into candidate_details values ('" +a+ "','" +b+ "','" +c+ "')");
    %>
    sucesssfully created New Account
    </body>
    </html>"

    bmahesh7feb wrote:
    org.apache.jasper.JasperException: /create_user.jsp(2,4) Invalid directiveAt line 2, character 4 of create_user.jsp there's an invalid directive. This is a plain code syntax error.
    <%@ //page errorPage="exceptionHandler.jsp"%>What are those slashes doing there? Do you think that those Java style comments outcomments the JSP line? It is JSP code, it is not Java code. Remove the whole line or use JSP comments.
    As for the remnant of your JSP code, there are a lot of flaws in there. First step to in the right direction would be to stop using scriptlets in JSP. Good luck.

  • [Newbie] Model2 JSP + JDBC + JSTL forEach

    Hi,
    This is my first post.
    I'm running into a bit of brain failure over decoupling my JSP view page from the specifics of the JDBC the model uses.
    I want to avoid the easy route of:
    Controller
    - interogates request as default main listing page.
    - runs a JDBC query
    - pops the ResultSet in the request
    - forwards to the mainlisting.jsp view
    JSP View
    - Uses a scriplet to iterate and display the contents of the results set as an HTML table.
    For a start I don't want to pass a ResultSet to the view page. I'd like to keep it completely ignorant of whether the application is using JDBC, XML or an EJB for it's data tier.
    My first smart? idea was to write an adapter for ResultSet that provides a standard List (or similar) interface, taking data from the ResultSet and returning 'domain' value objects instead of Rows.
    This presents a secondary problem however. In order to provide a List of beans around the result set I either need to copy the whole result set into an ArrayList or Vector on creation, or implement the entire List interface myself (<yawn>).
    So I figured if it's that hard, it can't be the correct way.
    Ultimately I'm after some type of Bean collection I can populate (or wrap around) a ResultSet, so that the following JSP will display the list.
    <ul>
    <c:forEach items="${theListOfItems}" var="item">
    <li><c:out value="${item.foo}" /> - <c:out value="${item.bar}" /></li>
    </c:forEach>
    </ul>
    Any pointers?
    Cheers
    Paul

    I'm quite pleased I was on the right track and I even accepted defeat in finding a pipelining way to iterating over the beans attached to the underlying result set and .. as you suggest .. loading it all into beans on creation.
    I ended up with this:
    package uk.co.cmm.tvrecorder.webapp;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.Date;
    @SuppressWarnings("serial")
    public class RecordingList extends ArrayList<Recording> {
         public RecordingList(ResultSet res) throws SQLException {
              while( res.next() ) {
                   Recording rec = new Recording();
                   rec.setId(res.getInt("id"));
                   rec.setChannel(res.getString("chan"));
                   rec.setProgName(res.getString("prog"));
                   rec.setPrio(res.getInt("prio"));
                   // Date-Times are stored as Unix long ints
                   // Why?  Legacy database - allows numerical comparison in legacy dvb recorder shell component.
                   // Possible future change to SQL DateTime but not just now.
                   Date d = new Date(res.getLong("start")*1000);
                   rec.setStart(d);
                   d = new Date(res.getLong("stop")*1000);
                   rec.setStop(d);
                   this.add(rec);
    }Which then allowed me to have:
    <table>
    <tr><th>Programme</th><th>Channel</th><th>Date</th><th>Start</th><th>Stop</th><th>Prio</th></tr>
    <c:forEach items="${recordings}" var="item">
         <c:choose>
                     <!-- when is running now -->
              <c:when test="${(now ge item.start) and (now lt item.stop)}">
                   <c:set var="style" value="background-color:red;" />
              </c:when>
              <c:otherwise>
                   <c:set var="style" value="background-color:white;" />
              </c:otherwise>
         </c:choose>
         <tr style="<c:out value="${style}" />">
              <td><c:out value="${item.progName}" /></td>
              <td><c:out value="${item.channel}" /></td>
              <td><fmt:formatDate type="date" dateStyle="FULL" value="${item.start}"  /></td>          
              <td><fmt:formatDate type="time" value="${item.start}" /></td>          
              <td><fmt:formatDate type="time" timeStyle="LONG" value="${item.stop }" /></td>          
              <td><c:out value="${item.prio}" /></td>     
         </tr>
    </c:forEach>That's that sorted, I think.... NEXT!
    Is this the correct way to put a var into an HTML attribute?
         <tr style="<c:out value="${style}" />">Cheers
    Paul

  • Newbie with JSP & JDBC questions

    Hi. I have a quick question. I have a client jsp page with a table, listing all the fields from my mySQL table called kellybclients. At the end of each row, I also have a submit button that I would like navigate the user to the campus jsp page that only shows the data associated with the client who's button they clicked on in the table. I'm trying to figure out how to pass this data from my JSP into the rowset.setCommand method in my connection/data bean. I am using a cached row set. Here's the code from my bean:
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package ETS;
    import java.sql.SQLException;
    import javax.sql.rowset.CachedRowSet;
    import java.util.ArrayList;
    import com.sun.rowset.CachedRowSetImpl;
    public class CampusDataBean {
        private CachedRowSet rowSet;
      public CampusDataBean() throws Exception
        Class.forName("com.mysql.jdbc.Driver");
        rowSet = new CachedRowSetImpl();
        rowSet.setUrl("jdbc:mysql://traderseven.nmsu.edu/is470Spring08?relaxAutoCommit=true");
        rowSet.setUsername("is470Spring08");
        rowSet.setPassword("1DoNtier");
        rowSet.setCommand("SELECT campid, clientid, campname,campcounty FROM kellybCampus WHERE clientid=?");
        CampusBean camp = new CampusBean();
        rowSet.setString(1, camp.getClientID());
        rowSet.execute();
      public ArrayList<CampusBean> getCampusList() throws SQLException
        ArrayList<CampusBean> campusList = new ArrayList<CampusBean>();
        rowSet.beforeFirst();
        while(rowSet.next())
          CampusBean campus = new CampusBean();
          campus.setCampID(rowSet.getString(1));
          campus.setClientID(rowSet.getString (2));
          campus.setCampName(rowSet.getString(3));
          campus.setCounty(rowSet.getString(4));
          campusList.add(campus);
        return campusList;
    public void addCampus(CampusBean campus) throws SQLException
        rowSet.moveToInsertRow();
        rowSet.updateString(1,campus.getCampID());
        rowSet.updateString(2,campus.getClientID());
        rowSet.updateString(3,campus.getCampName());
        rowSet.updateString(4,campus.getCounty());
        rowSet.insertRow();
        rowSet.moveToCurrentRow();
        rowSet.acceptChanges();
    }I'm sorry if this is too vague. I'd appreciate any help, fixes, or pointers on where to learn how to do this. Thank you again.
    KellyJo

    So the button should be a Submit button for a form. There are a couple of different methods for doing this:
    1) Each row on the table can be a different form, each form uses the same action (servlet) target and has a hidden input with a unique identifier for each of the clients:
    <table>
      <tr><form action="selectClient" method="post"><td> etc </td><td><input type="hidden" name="id" value="1"/><input type="submit"/></td></form></tr>
      <tr><form action="selectClient" method="post"><td> etc </td><td><input type="hidden" name="id" value="2"/><input type="submit"/></td></form></tr>2) Use a single form with a button type=submit for each row with different values (Note: This is broken in IE7 so you probably shouldn't use it)
    <table><form action="selectClient" method="post">
      <tr><td> etc </td><td><button type="submit" name="id" value="1">Submit</button></td></tr>
      <tr><td> etc </td><td><button type="submit" name="id" value="2">Submit</button></td></tr>3) Use a single form, have a hidden value with a blank value. Each row has a submit button with a javascript onclick method that sets the form's hidden value to one appropriate to the row, then submits the form. I won't show you this code but there are examples on the web.
    4) Use a single form with an input="submit" element on each row. Each button would have a different name with the ID info encoded in it, then you would have server-side code that takes parameters, finds the right one and parses out the proper row to edit:
    <table><form action="selectClient" method="post">
      <tr><td> etc </td><td><input type="submit" name="submit__id_1"/></td></tr>
      <tr><td> etc </td><td><input type="submit" name="submit__id_2"/></td></tr>I think most people end up doing some variant of 3, which I don't like because I hate to rely on JavaScript to make my web apps work properly. I would prefer 4, which takes more work on the server side (which I like better) but 1 works just as well with a lot more typing and uglier HTML code. Actually, I would like 2 the best because that is pretty much what the <button> element was designed for, but Microsoft screwed that up.

  • Using JSP & JDBC driver for SQL Server 2000 on Red Hat

    I successfully have a .jsp app running on windows server 2000 using JDBC
    driver for SQL Server 2000. Which I installed in order to the following
    Red Hat:
    http://msdn.microsoft.com/MSDN-FILES/027/001/779/install.htm
    I moved the .jsp app over to the Red Hat 9 server running Tomcat, while
    keeping the MS SQL 2000 on windows. The issue I have is setting up the
    JDBC driver for SQL Server 2000 on the Red Hat server.
    I created a folder called /usr/java/MSSQLdriver and unzipped the tar file with
    the driver for SQL Server 2000. And ran the install.ksh script.
    The /usr/java/MSSQLdriver/lib has the following files within it:
    msbase.jar, msutil.jar, & mssqlserver.jar
    I chmod 0777 each of the *.jar files.
    I then went into /etc/profile.d/tomcat.sh and adding the following:
    CLASSPATH=.;/opt/msSQLjdbc/lib/msbase.jar;/opt/msSQLjdbc/lib/msutil.jar;/opt/msSQLjdbc/lib/mssqlserver.jar
    Each time I login and pull up the termial I get the following error:
    bash: /opt/msSQLjdbc/lib/msbase.jar: cannot execute binary file
    bash: /opt/msSQLjdbc/lib/msutil.jar: cannot execute binary file
    bash: /opt/msSQLjdbc/lib/mssqlserver.jar: cannot execute binary file
    And can't connnect to the database within the .jsp app.
    Is there anyone out there using DBC driver for SQL Server 2000 on the Red Hat server?
    Michael

    Sorry, I needed to correct some information of where the drivers were installed.
    I created a folder called /usr/java/MSSQLdriver/new and untar the Microsoft file with the driver for SQL Server 2000. I ran the install.ksh script "sh install.ksh"
    installed the driver into the default directory "/opt/msSQLjdbc".
    The /opt/msSQLjdbc/lib has the following files within it:
    msbase.jar, msutil.jar, & mssqlserver.jar
    Michael

  • Formatting data in table - jsp & jdbc

    Hey there friends!
    I was having a little problem formatting data and I was looking for help!
    I want to format the data from jdbc as follows on a jsp page
    THIS IS REPORT TO GENERATE
    Name | Worked | Refused | Training | CarryOver
    Jim | 10 | 5 | 2 | 5
    Bob | 20 | 5 | 10 |
    The resultset that I retrieve from my database is like this
    RESULTSET
    ID | Name | Type | Hours | CarryOver
    1 | Jim | Worked | 10 | 5
    1 | Jim | Refused | 5 | 5
    1 | Jim | Training | 10 | 5
    2 | Bob | Worked | 20 | 10
    2 | Bob | Training | 5 | 10
    Can anyone suggest what can be a done here?

    As you have learnt something it is only fair for me for reciprocate.
    The code example I gave you was psuedocode - not real java. You need to add in a couple more things to make it work correctly.
    First we want to create an entry in the hash, iff there is no record already there, otherwise, we want to get the value and add our new value to it (let's say the map is called map):
    String key = record.name + "/" + record.type;  // Using combination string as the key - simplest solution
    Long hours = map.get(key);
    if (hours == null) {
       hours = new Long(record.hours);
    } else {
       hours = new Long(hours.getValue() + record.hours);
    map.put(key, hours);It would be better to use your own class to hold the long value - as this would save all the construction calls.

  • Very very urgent. Please help. JSP - JDBC connectivity.

    Hi.
    Can any one guide me the methods and steps to be followed for storing the input entered on a JSP front end into a database. Also help is needed for retrieving the data from the table and displaying on the front end. Please reply as early as possible as I am stuck in my work due to this reason. Please do reply as soon as possible,.
    Regards
    Venkat

    What part don't you understand?Here are my guesses about what the OP doesn't understand:
    >
    JSP? Yes.
    JDBC? Yes.
    Relational databases? Yes.
    Deploying Web apps? Yes.
    Your servlet/JSP container? Yes.
    What? Yes.Again, just wild guesses. :-)

  • Need serious help with JSP + JDBC/Database connection

    Hey all,
    I have to build an assignment using JSP pages. I am still pretty new and only learning through trial and error. I understand a bit now, and I have managed to get a bit done for it.
    I am having the most trouble with a Login Screen. The requirements are that the a form in a webpage has Username/Number and Password, the user clicks Login, and thats about it. The values for the username/number and password NEED to come from the database and I cannot manage to do this. The thing I have done is basically hardcode the values into the SQL statement in the .jsp file. This works, but only for that one user.
    I need it so it checks the username/number and password entered by the user, checks the database to see if they are in it, and if so, give access. I seriously am stuck and have no idea on what to do.
    I dont even know if I have made these JSP pages correct for starters, I can send them out if someone is willing to look/help.
    I have setup 3 other forms required for the assignment and they are reading data from the db and displaying within tables, I need to do this with non-hardcoded values aswell. Im pretty sure I need to use for example 'SELECT .... FROM .... WHERE username= +usrnm' (a variable instead of username="john" , this is hardcoded), I just CANNOT figure out how to go about it.
    Its hard to explain through here so I hope I gave enough info. A friend of mine gave some psuedocode i should use to make it, it seems ok to follow, its just I do not know enough to do it. He suggested:
    get the username and pass from the env vars
    open the db
    make an sql (eg SELECT user, pass FROM users WHERE user = envuser)
    index.jsp points to login.jsp
    login.jsp get the vars you put into index.jsp
    opened the db
    is the query returns nothing - then the user is wrong
    OR if the passwords dont match
    - redirect back to index.jsp
    if it does match
    - set up a session
    - redirect to mainmenu.jsp
    Anyway, thanks for any help you can give.
    -Aaron

    Hi,
    Try this... it may help you...
    mainMenu.jsp
    <html>
    <body>
    <form method="POST" action="login.jsp">
    Username: <input type="text" name="cust_no">
    <p>
    Password: <input type="password" name="password">
    <p>
    <input type="submit" value="LOGIN">
    </form>
    </body>
    </html>
    login.jsp
    <%@ page import="java.io.*, java.sql.*"%>
    <html>
    <body>
    <%
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection connection = DriverManager.getConnection("jdbc:odbc:rocky");
    Statement statement = connection.createStatement();
    String query = "SELECT cust_no, password FROM customers WHERE cust_no='";
    query += request.getParameter("cust_no") + "' AND password='";
    query += request.getParameter("password") + "';";
    ResultSet resSum = statement.executeQuery(query);
    if (request.getParameter("cust_no").equalsIgnoreCase(resSum.getString("cust_no") && request.getParameter("password").equalsIgnoreCase(resSum.getString("password"))
    %>
    <h2>You are logged in!</h2>
    <%
    else
    %>
    <h2>You better check your username and password!</h2>
    <%
    }catch (ClassNotFoundException cnfe){
    System.err.println(cnfe);
    }catch (SQLException ex ){
    System.err.println( ex);
    }catch (Exception er){
    er.printStackTrace();
    %>
    </body>
    </html>
    I didn't check the code that I wrote. So you may have to fix some part of it. Also this may not be the best solution, but it will help you to understand the process easily.
    The more efficient method is to check whether the result set returned from the database is null or not.... I hope you got the idea... Good luck!
    Rajesh

  • Servlet proposal: using JSP/JDBC & An Applet Gateway?

    Hello all,
    I'm in the process of upgrading a very basic static webpage to a JSP-automated webpage dynamically updated at certain times.I'll post more complete details soon ,but i'll give u a rough outline of the situ.
    I need a basic database : MS ACCESS (since expected site net-traffic will be low).The stock-list will bw on such a database which is access/updated by the JSP contoiusly.There are two methods I could use-
    1) A single database accessed by both the JSP Servlet & Office PC Application (stock control).
    problem: which location is better for the database: Server or networked PC?
    2)2 two identical databases residing on the Office PC(stock-control) & JSP server(customer orders).There will be a data-exchange between the 2 databases several times a day.The Office PC receives the orders list(demand) while the JSP receves the latest stock-list(supply).
    problem: should transfer be auto time-set or manual command (from Office PC using a private webpage linked to the JSP)
    Should one use several servlets: eg: one for HTML writing another for JDBC communication?
    Thanks!
    Regards,
    Nemo

    1) A single database accessed by both the JSP Servlet
    & Office PC Application (stock control).If you have 2 clients accessing the same data, a single database should be fine.
    problem: which location is better for the database:
    Server or networked PC?Access is a very basic DB so a networked PC is okay, it doesn't matter as ODBC lets you define where the database is your trying to connect to.
    Should one use several servlets: eg: one for HTML
    writing another for JDBC communication?Following the MVC2 concept, JSP's for front end views, servlets for processing business logic. Using Access you can create a basic class that can construct a Connection pool to your database just make sure you handle your transactions properly or else you'll end up with duplicate/corrupted data.
    Cheers,
    Anthony

  • I have a requirement with select and text boxes. JSP / JDBC

    I have a Combo Box which iswritten by a JSP by connecting to DB!
    When i click on a <option> corresponding the other two text boxes must be loaded with data!
    if i have list of EmpID in <select>, in one text box i should get his CITY and other Occupation !
    What i thought is .... getting all the data from database. select empid from emp and write a combo and select city,occupation from emp, intp ARRAYLISTs!
    function updatData(){
    var index=document.projalloc.associateid.selectedIndex;
    }if i onSelect=updateData(), (i will get index of empid,as it is a combobox) using which i have to retrieve the values of city and occupation !!
    BUT HOW !
    I am gettin the index of empid but how to get the data into textbox !!!!

    well there are many ways of doing this.
    1).Render all the data corresponding to each employee at a time.By making a javascript arrays and try to get back the data from there.
    2).Save the ArrayList of DTO beans in the scope of session.Use AJAX call a CGI(Servlet/JSP action) fetch the values from the session render the response as XML now parse the XML data using javascript DOM and then update the consecutive textboxes.
    Just as an example checkout my answer in the below post.It was an example given for a dependent drop downs.however, we can definately use the same concept to update textboxes too.
    http://forum.java.sun.com/thread.jspa?threadID=5209661&messageID=9844137#9844137
    Hope that might help :)
    REGARDS,
    RaHuL

  • JSP JDBC Problem

    Hello All,
    I have created a small application using jsp and servlets with Oracle 10g as back end database and hosted on the oracle application server 10g. Database is installed on AIX machine and my application server is installed on a windows machine. When 4 to 5 users access the application simultaneously, it starts generating error "ORA-12519: TNS:no appropriate service handler found" and application becomes unaccessible. I have properly closed connections where ever opened to read or updated the database. Can any body suggest a solution?
    Thanx

    ORA-12519: TNS:no appropriate service handler found
    Cause: The listener could not find any available service handlers that are appropriate for the client connection.
    Action: Run "lsnrctl services" to ensure that the instance(s) have registered with the listener, and are accepting connections.

  • Jsp/jdbc - Tomcat

    My requirement is once i issue a request from my jsp (the request is a sql query) it has to hit the database and should
    return the number of affected row but should not commit it . In the next request from jsp the user will either hit
    commit button or rollback button and based on the request it will either commit or rollback .In order to acheive this i
    believe i have use the same connection object for both request.
    I know http is stateless and i have to use the same connection object for both the request .
    1) How can i use the same connectionobject in both request.?
    2) What if the user did not click commit or rollback button . How can i expire the connection object that was opened during first request

    I think you might want to read up on this on google:
    optomistic concurency sql
    I think the best solution is to get/use/close your connection as fast as possible (in a try/catch/finally block) within the same function.
    In your database table, add a new column called 'version'. Each time someone updates a record in the table, increase the value of version by one for that record.
    Now, in your design, read the record (including version number), display it to the user. Later, when the user clicks the update button, see if the version number has changed when you go to update.
    If so, inform the user that the record has changed in the meantime. Usually, end users work on different records and seldom the same record at the same time so the collision doesnt occur often.
    Example
    sql= update person set firstName='john' where person_id=434 and version=34
    The above will return a value of '1' if it was updated, '0' if it wasn't.
    Note there is no need to rollback with this method.
    Transaction advice:
    Use a transaction if:
    1) You are updating/inserting/deleting more than one record in a table and need to rollback if any one record update/insert/delete fails (or the version number shows it was changed per the above example).
    2) you need to query one table and update the same table or some another table and want to ensure no records were changed between the query and update (treat them as an atomic operation).
    3) you need to create more than one query to query several tables and want to ensure no data was changed in any table while doing the queries.
    No tranaction if:
    1) you query more than one table using one sql statement (a join).
    See also database section at http://www.javapractices.com/home/HomeAction.do

Maybe you are looking for