Database access in JSP?

Can I easily access MS access using JSP? If it is, what kind of drive should be used to access the MS Access database?
Thank you so much!

<%!
// define database parameters
String host="localhost";
String user="";
String pass="";
String db="";
String conn;
%>
<%
Class.forName("org.gjt.mm.mysql.Driver");
// create connection string
conn = "jdbc:mysql://" + host + "/" + db + "?user=" + user + "&password=" +
pass;
// pass database parameters to JDBC driver
Connection Conn = DriverManager.getConnection(conn);
// query statement
Statement SQLStatement = Conn.createStatement();
This is when accessing a database in a JSP, not a javabean... Try searching this forum, there are LOTS of topics about this.

Similar Messages

  • Database access with JSP custom tags

    i have created one file in which i am making the connection with mysql data base with con.mysql.jdbc.Driver.and usking J connector and that i'm doing with custom tag.this is the error which i'm getting in tomcat.
    and the tag handler class and TLD file and jsp file is below
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    javax.servlet.ServletException: javax.servlet.jsp.JspException: null
    org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl .java:841)
    org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.j ava:778)
    org.apache.jsp.DbTry_jsp._jspService(org.apache.jsp.DbTry_jsp:72)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:99)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:325)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:245)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    root cause
    java.lang.NullPointerException
    Try.Connect.<init>(Connect.java:26)
    sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    java.lang.reflect.Constructor.newInstance(Unknown Source)
    java.lang.Class.newInstance0(Unknown Source)
    java.lang.Class.newInstance(Unknown Source)
    org.apache.jasper.runtime.TagHandlerPool.get(TagHandlerPool.java:116)
    org.apache.jsp.DbTry_jsp._jspx_meth_db_connect_0(org.apache.jsp.DbTry_jsp:84)
    org.apache.jsp.DbTry_jsp._jspService(org.apache.jsp.DbTry_jsp:62)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:99)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:325)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:245)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    note The full stack trace of the root cause is available in the Apache Tomcat/5.5.4 logs.
    Apache Tomcat/5.5.4
    Tag handler class
    package Try;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import javax.servlet.jsp.JspException;
    import javax.servlet.jsp.JspWriter;
    import javax.servlet.jsp.PageContext;
    import javax.servlet.jsp.tagext.TagSupport;
    import java.sql.*;
    public class Connect extends TagSupport {
    private String driver = "com.mysql.jdbc.Driver";
    private String dbtype = "mysql";
    private String host = "localhost";
    private String username = "root";
    private String password = "203131";
    private String database = "compose";
    private String scope = "page";
    private String id = "";
    JspWriter out = pageContext.getOut();
    public void setDriver(String str) {
    driver = str;
    public void setDbtype(String str) {
    dbtype = str;
    public void setHost(String str) {
    host = str;
    public void setUsername(String str) {
    username = str;
    public void setPassword(String str) {
    password = str;
    public void setDatabase(String str) {
    database = str;
    public void setScope(String str) {
    scope = str;
    public void setId(String str) {
    id = str;
    public int doStartTag() throws JspException {
    try {
    Class.forName("com.mysql.jdbc.Driver");
    String url= "jdbc:" + dbtype + "://" + host + "/" + database;
    Connection connection = DriverManager.getConnection(url,username,password);
    out.println("right ;;one");
    catch (SQLException e1) {
    System.out.println("Error in HeadingTagv: " + e1);
    catch (Exception e) {
    System.out.println("Error in HeadingTag: " + e);
    return SKIP_BODY;
    TLD is lib.tld
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE taglib
    PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
    "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_2.dtd">
    <taglib>
    <tlib-version>1.0</tlib-version>
    <jsp-version>1.2</jsp-version>
    <short-name>db</short-name>
    <display-name>Database Tags</display-name>
    <description>
    A set of tags for working with SQL database access
    </description>
    <tag>
    <name>connect</name>
    <tag-class>Try.Connect</tag-class>
    <body-content>empty</body-content>
    <description>
    </description>
    <attribute>
    <name>driver</name>
    <required>false</required>
    <rtexprvalue>true</rtexprvalue>
    <description>
    </description>
    </attribute>
    <attribute>
    <name>dbtype</name>
    <required>false</required>
    <rtexprvalue>true</rtexprvalue>
    <description>
    </description>
    </attribute>
    <attribute>
    <name>host</name>
    <required>false</required>
    <rtexprvalue>true</rtexprvalue>
    <description>
    Can be given by a run-time expression.
    Host name of the computer where database is located.
    Default is "localhost".
    </description>
    </attribute>
    <attribute>
    <name>username</name>
    <required>false</required>
    <rtexprvalue>true</rtexprvalue>
    <description>
    Can be given by a run-time expression.
    Username for logging onto the database.
    Default is "root".
    </description>
    </attribute>
    <attribute>
    <name>password</name>
    <required>false</required>
    <rtexprvalue>true</rtexprvalue>
    <description>
    Can be given by a run-time expression.
    Password for logging onto the database.
    Default is the empty string.
    </description>
    </attribute>
    <attribute>
    <name>database</name>
    <required>false</required>
    <rtexprvalue>true</rtexprvalue>
    <description>
    Can be given by a run-time expression.
    The name of the database that will be used for
    the SQL commands. Default is no database specified.
    </description>
    </attribute>
    <attribute>
    <name>id</name>
    <required>false</required>
    <description>
    </description>
    </attribute>
    <attribute>
    <name>scope</name>
    <required>false</required>
    <description>
    </description>
    </attribute>
    </tag>
    </taglib>
    JSP file is
    <%@ taglib uri="/WEB-INF/lib.tld" prefix="db" %>
    <html>
    <body>
    <db:connect username="root" password="203131" database="compose" />
    </body>
    </html>

    Answered in your other post:
    http://forum.java.sun.com/thread.jspa?threadID=608780&tstart=0

  • Database Access through JSP

    Hi im trying to access my ORACLE database through a jsp program. The page loads up in the browser, no errors or anything like that, but i get no output.
    I am running things on localhost with TomCat 3.2.3
    Here is the code, any help gratefully appreciated.
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <HTML>
    <HEAD>
    <TITLE>Testing Database Access</TITLE>
    </HEAD>
    <BODY BGCOLOR="#FDF5E6" TEXT="#000000" LINK="#0000EE"
    VLINK="#551A8B" ALINK="#FF0000">
    <CENTER>
    <TABLE BORDER=5 BGCOLOR="#EF8429">
    <TR><TH CLASS="TITLE">
    Testing Database Access</TABLE>
    </CENTER>
    <P>
    <P>
    Here Is what Might be in the Database
    <P>
    <%@ page language="java" %>
    <%@ page import="java.util.*" %>
    <%@ page import="oracle.jdbc.driver.*" %>
    <%@ page import="java.io.*" %>
    <%@ page import="java.sql.*" %>
    <%
         try
    %>
    <%
         DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
         String username = "Donnchadh", password = "zcbu5mya";
         Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@kiwi.isg.computing.dcu.ie:1521:kiwi",username,password);
         java.sql.Statement stmt = conn.createStatement();
         String query = "SELECT * FROM PERSONALS";
         ResultSet rs = stmt.executeQuery(query);
         while(rs.next())
              int ccount = rs.getMetaData().getColumnCount();
              for( int i = 1; i <= ccount; i++ )
                   System.out.print(rs.getString(i)+"\t");
              System.out.println();
    %>
    <%
         rs.close();
         stmt.close();
         if(conn != null)
              try
                   conn.close();
              catch(Exception e)
                   return;
         catch(Exception e)
              return;
    %>
    <P>
    </BODY>
    </HTML>
    I have also tried to access columns directly with this code in the while loop
    while(rs.next())
                        String Title = rs.getString("title");
                        String FName = rs.getString("fname");
                        String LName = rs.getString("lname");
                        String Phone = rs.getString("phone1");
                        String Phone2 = rs.getString("phone2");
                        String Addr = rs.getString("addr");
                        String County = rs.getString("county");
                        String Country = rs.getString("country");
                        out.println("<tr><td>" + Title + "</td><td>" + FName + "</td><td>" + LName
                        + "</td><td>" + Phone + "</td><td>" + Phone2 + "</td></tr>" + "</td></tr>" + Addr
                        + "</td></tr>" + County + "</td></tr>" + Country + "</td></tr>" );

    i give a servlet access to oracle ,that have test ok!
    import java.sql.*;
    import javax.servlet.*;
    import javax.sql.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    public class TestServlet1 extends HttpServlet {
    private static final String CONTENT_TYPE = "image/jpeg; charset=GBK";
    //Initialize global variables
    String strRno =null;
    ResultSet rs=null;
    byte [] buf=null;
    InputStream in;
    int IntNo;
    public void init() throws ServletException {
    //Process the HTTP Get request
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType(CONTENT_TYPE);
    // PrintWriter out = response.getWriter();
    // System.out.println("TEst database prepaired ok��");
    strRno = request.getParameter( "PictNo" );
    IntNo = 0;
    if( strRno != null ) {
    try { IntNo = Integer.parseInt( strRno ); }
    catch( NumberFormatException e ) {
    strRno = null;
    System.out.println("��������������������"); }
    else
    System.out.println("��������������������");
    if( strRno == null ) {
    // response.sendError( HttpServletResponse.SC_NOT_FOUND );
    return;
    try {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    catch (ClassNotFoundException ex2) {
    //      out.println("TEst2��");
    // System.out.println("TEst2�� ex2��");
    String url="jdbc:oracle:thin:@erdos00:1521:erdos";
    Connection con = null;
    try {
    con = DriverManager.getConnection(url, "system", "manager");
    catch (SQLException ex1) {
         //out.println("TEst�� ex1");
         System.out.println("TEst�� ex1��");
    // PreparedStatement sql=con.PrepareStatement("select photo from blob_test WHERE rno = IntNo" );
    PreparedStatement sql = null;
    try {
    sql = con.prepareStatement("select photo from blob_test WHERE rno = 14 ");
    // sql = con.prepareStatement("select photo from blob_test WHERE rno = " +"+ IntNo +" );
    catch (SQLException ex) {
         //out.println("TEst�� ex");
         System.out.println("TEst�� ex��");
    //method prepareStatement(sting) not found in interface java.sql.connection
    // sql.setInt( 1, rno );
    try {
    rs = sql.executeQuery();
    catch (SQLException ex3) {
         //out.println("TEst�� ex3");
         System.out.println("TEst�� ex3");
    System.out.println("TEst database operate ok��");
    // out.println("TEst database operate ok��");
    //��������������������
    try {
    if (rs.next()) {
    buf = rs.getBytes(1);
    in = rs.getBinaryStream("photo");
    else {
    buf = new byte[0];
    }catch (Exception e){
    //throw e;
    response.reset();
    //������image/jpeg������������������������
    response.setContentType("image/bmp");
    // ��bmp��jpeg
    byte[] b = new byte[1024*1024];
    int len;
    while((len=in.read(b)) >0)
    response.getOutputStream().write(b,0,len);
    OutputStream out1 = response.getOutputStream();
    out1.flush();
    out1.write(buf);
    in.close();
    try {
    rs.close();
    catch (SQLException ex4) {
    // out.println("<html>");
    // out.println("<img src='http://192.168.0.1/examples/servlet/TestServlet1?PictNo="+IntNo+"'>");
    // out.println("</html>");
    out.println("<html>");
    out.println("<head><title>TestServlet</title></head>");
    out.println("<body bgcolor=\"#ffffff\">");
    out.println("<p>The servlet has received a GET111111111. This is the reply.</p>");
    out.println("</body></html>");
    //Process the HTTP Post request
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType(CONTENT_TYPE);
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head><title>TestServlet</title></head>");
    out.println("<body bgcolor=\"#ffffff\">");
    out.println("<p>The servlet has received a POST. This is the reply.</p>");
    out.println("</body></html>");
    //Process the HTTP Put request
    public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //Process the HTTP Delete request
    public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //Clean up resources
    public void destroy() {
    hope u can get some thing from that

  • Database Access from JSP - Is it correct?

    From a JSP Page, we need to retreive data from the database. We have our own application specific API commands to retreive data from database. We have doubts in using this API commands.
    Approach 1:
    From the jsp, send the query details to a Java file (BO). From the java file (BO), call the database and retreive the data
    Approach 2:
    Use the API command directly from the jsp page to retreive details from the database.
    In both approaches, the same API command is going to be used. We just want to know is there any advantage in calling the database through the java file (BO) instead of directly from the jsp?
    Regards,
    R.Aravinth

    Thanks Ram. But we are not going to have any complex
    codes written for data retreival. We just epxect a
    single line of code which will call database and that
    API command will return us a storage variable which
    we will use for displaying purpose.
    ok take a look at this
    //code to display lot of other stuff
    <%
        try {
           //code to access db and get data;
        catch(SomeException e){
            //oh-oh you are already on the display logic and have output a lot of stuff
            //how do you handle this
    %>versus this
    //code in some handler or bean
       try{
               //code to get data
              //set an attribute to enable a redirect to jsp page
        catch(Exception e){
              //handle exception, log ?
              //set an attribute to enable a redirect to error page
    Anyways, i wanted to know will the performance of the
    page improve if we call the database from a separate
    java rather than directly from jsp?As evnafets said, the answer is no. It may even be faster :)
    cheers,
    ram.

  • Database Access from JSP

    I'm trying to access a SQL Server database through an ODBC connection on a JSP page and having difficulties. This is the code that I'm using:
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection conn = DriverManager.getConnection("jdbc:odbc:ODBCConnection", "username", "password");
    Statement stmt = conn.createStatement();
    ResultSet results = stmt.executeQuery(
    "SELECT numUserID, txtUsername, txtPassword FROM tblUsers");
    while (results.next()) {
    int DBuserid = results.getInt("numUserID");
    String DBusername = results.getString("txtUsername");
    String DBpassword = results.getString("txtPassword");
    conn.close();
    } catch (Exception exc) {                              
    out.println ("Exception \"" + exc + "\" occured....<br>");
    exc.printStackTrace();
    I've got two servers I'm testing it on. One is the IBM WebSphere 3.5 on Windows NT 4 and the other one is the Oracle 9i Server (Apache) with java support on Windows 2000. The code works fine on the Oracle server, but does not work on the WebSphere. I am getting a "java.sql.SQLException: [Microsoft][ODBC SQL Server Driver]Client unable to establish connection" exception. The problem is that I need to run this thing on the WebSphere server.
    I guess this might have something to do with the Java server differences or OS differences, but I don't know what that could be. I'm sure there's something that I'm not doing right, I just need some help figuring out what that is. I'd appreciate any help anyone can provide. Thanks.

    ODBC connection is set up the same on both servers and works with Access. In fact, I have tried to put the same code that I'm trying to use in a regular text java file, it compiled and ran on that same server. I've got a feeling I have the Websphere server setup wrong, but I don't know exactly what and how to fix it.
    Thanks.

  • Database access with JSP

    Hello,
    i have a Java Server Page where i fill in some data in a formular. I want to put these data (only two strings) in a database. I already use a servlet to give this data to a (already existing) stateless session bean. I also created and deployed an sda, so that the table exists in the database.
    But i do not understand, what to do next - how to use an entity bean to fill the table.
    Can anyone give me some hints?
    Thanks,
    André

    Hi Andre,
    you need to retrieve the Home Object of your entity bean and use it to create, the same way you create your session bean.
    Example:
    InitialContext initialContext = new InitialContext();
    EjbObject myEjb = null;
    try {
      java.lang.Object objRef = initialContext.lookup(EjbHome.JNDI_NAME);
    EjbHome home = (EjbHome)PortableRemoteObject.narrow(objRef, EjbHome.class);
             myEjb = home.create();
    } catch (Exception) {
             initialContext.close();
    The lookup to the home object can vary, you might also have helper classes for that, it depends on your application server, API and architecture.
    But however the call or whichever the server, you basically need to retrieve the home object of your entity bean and use the method create() - with any required parameters. Pretty much the same way you create a session bean.
    Hope this helps.
    regards,
    Dionisios

  • How to use taglibs in JSP for Database access

    Hi
    Could any one please tell me how to use taglibs in JSP for Database access
    with regrds
    Jojo

    This is a sample how to connect to a MySQL database with JSTL 1.0:
    <%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
    <%@ taglib uri="http://java.sun.com/jstl/sql" prefix="sql" %>
    <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>JSTL MySQL</title>
    <link href="styles.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
    <c:catch var="e">
    <sql:setDataSource var="datasource" url="jdbc:mysql://Your_Server_Name_Here/You_Schema_Here"
                           user="Your_Username_Here" password="Your_Password_Here"
                           driver="com.mysql.jdbc.Driver"/>
    <c:out value="datasource= ${datasource},  Class = ${driver.class}"/>
    <br />
    <br />
    <sql:query var="deejays" dataSource="${datasource}">SELECT * FROM Your_Table_Name_Here</sql:query>
    <table>
    <%-- Get the column names for the header of the table --%>
    <c:forEach var="columnName" items="${deejays.columnNames}"><th><c:out value="${columnName}"/></th></c:forEach>
    <tbody>
    <%-- Get the value of each column while iterating over rows --%>
    <c:forEach var="row" items="${deejays.rows}">
      <tr><c:forEach var="column" items="${row}">
            <td><c:out value="${column.value}"/></td>
          </c:forEach>
      </tr>
    </c:forEach>
    </tbody>
    </table>
    </c:catch>
    <br />
    <br />
    <c:if test="${e!=null}"><span class="error">Error</span>�
      <c:out value="${e}" />
    </c:if>
    </body>
    </html>And this thread might help you:
    http://forum.java.sun.com/thread.jspa?threadID=639471&tstart=44

  • Jsp database access using odbc - please help

    Hi friends,
    I�m trying a very simple database access program in jsp data base access using odbc. Odbc has to be used because thin driver or other drivers may not be available in every system of our college and as you know it's not that easy to make changes to those systems. My problem is so simple. I always get an exception in my program.
    My jsp content is as simple as:
    <%@ page import="java.lang.*,java.sql.*,java.io.*,registerbean" %>
    <jsp:useBean id="db" class="registerbean" scope="session"/>
    <%
    String str="insert into reg values('" + db.getName() + "','" + db.getUname() + "','" + db.getPass() + "'," + db.getAge() + ",'" + db.getSex() + "','" + db.getAdd() + "','" + db.getUgcourse() + "','" + db.getUgqual() + "'," + db.getPer() + ",'" + db.getIadd() + "')";
    try
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con=DriverManager.getConnection("jdbc:odbc:yogaesh","scott","tiger");
    Statement stmt=con.createStatement();
    stmt.executeUpdate(str);
    }catch(Exception e1){out.println(str);};
    %>
    the table reg has the structure:
    Name Null? Type
    CNAME VARCHAR2(20)
    UNAME VARCHAR2(20)
    CPSWD VARCHAR2(20)
    CONFPASS VARCHAR2(20)
    CAGE NUMBER
    CSEX VARCHAR2(5)
    CADD VARCHAR2(100)
    COURSE NUMBER
    CQUAL VARCHAR2(10)
    CPER NUMBER
    IADD VARCHAR2(100)
    The registerbean.java file is as below: (This seems to work fine because I tried printing the values using <%= %> tag and it worked out fine and moreover the query string is intact.)
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    public class registerbean
    private String name,uname,pass,cpass,age,sex,add,ugcourse,ugqual,per,iadd,otherugqual,ccode;
    public void setName(String a)
    name=a;
    public void setUname(String a)
    uname=a;
    public void setPass(String a)
    pass=a;
    public void setCpass(String a)
    cpass=a;
    public void setAge(String a)
    age=a;
    public void setSex(String a)
    sex=a;
    public void setAdd(String a)
    add=a;
    public void setOtherugqual(String a)
    otherugqual=a;
    public void setCcode(String a)
    ccode=a;
    public void setUgcourse(String a)
    ugcourse=a;
    public void setUgqual(String a)
    ugqual=a;
    public void setPer(String a)
    per=a;
    public void setIadd(String a)
    iadd=a;
    public String getName()
    return(name);
    public String getUname()
    return(uname);
    public String getPass()
    return(pass);
    public String getCpass()
    return(cpass);
    public String getAge()
    return(age);
    public String getCcode()
    return(ccode);
    public String getSex()
    return(sex);
    public String getAdd()
    return(add);
    public String getUgcourse()
    return(ugcourse);
    public String getUgqual()
    return(ugqual);
    public String getPer()
    return(per);
    public String getIadd()
    return(iadd);
    public String getOtherugqual()
    return(otherugqual);
    I initially thought the problem was with str but then str seems to be perfect and I get a string of the form �insert into reg values('c','c','c',98,'Male','c','B.Tech, Applied Artificial Neural Networks','HSC',9898,'h')� which I verified through a javascript debugger. The session scope used is to get values through the db bean from another jsp file. The problem is in the executeUpdate() line of this code. I even tried changing the updation table, but in vain. What could be done to rectify this? Please help me out and please do remember that I have no option but to use odbc.
    Thanks in advance.
    R. Yogaesh.

    I didn't verify the type of exception and i'm now going to do that, but then when the string is as perfect as needed, what is the need for a prepared statement? What is the basic difference between the two? And basically what is the problem with this piece of code which creates an exception? Please reply as soon as possible.
    Thankyou very much.
    R. Yogaesh.

  • JSP example with database access

    Is there a good example of a JSP portlet doing Oracle database access? Thanks

    David,
    Thanks for the suggestion. We'll schedule that on our list of new sample portlets.
    But as a sidenote, the Database access would really be no different from any standard JDBC calls to connect to and query the database.

  • Database access in a MVC architecture

    Hi!
    I'm a bit confused with regards to where the database access code should be put in a MVC architecture. From reading various articles and posts on this forum, there seem to be a lot of different opinions.
    Some seem to put the database access code in the controller servlet(or JSP), while some seem to use helper classes from the JavaBeans, while a few people even seem to access the database directly from the JavaBean.
    My questions is: What is the best place to put the database stuff in a MVC architecture? An explanation as to why a particular solution is the best would be great..
    Thanks!
    regards,
    Vidar

    Let's say I have a class called Department that contains methods like getName(), getId(), setName(), etc... The Department class is my business object. To save and load Departments from a database, I have a class called DepartmentManager. The DepartmentManager saves and loads the departments to the database, and has methods like saveDepartment(), saveDepartments(), loadDepartment(), getDepartments(), etc... In some cases, my manager classes also caches the results so they don't have to load from the database each time. Often times, the manager class is a singleton. My Department class has no idea how it is persisted, or that it is part of a cache. It just knows about itself. The DepartmentManager is resonsible for managing all the persistance and lookup functionality for Departments.
    Therefore, if I have a JSP page that needs to display Departments, my code might look like:
    DepartmentManager dm = DepartmentManager.getManager();
    ArrayList listDepartments = dm.getDepartmentList();
    for (int i = 0; listDepartments != null && i < listDepartments.size(); i++) {
         Department dept = (Department)listDepartments.get(i);
         out.println("<option value=\"" + dept.getId() + "\">" + dept.getName());
    }If I had a specific Department I needed, I would get it as follows:
    DepartmentManager dm = DepartmentManager.getManager();
    Department dept = dm.getDepartment(nId);

  • Slow database access across network

    I have a postgresql database setup on a server machine and have written a java program in netbeans that accesses it. The problem i have is that running the jar created by netbeans from any other machine on the network has really slow database access but running the program from netbeans itself is fine. Running the jar on the server machine is also fine.
    Anyoner got any idea as to why this could be?
    Tom

    I don't know if this will help, I'm just wading into writing my own java apps to hit a SQL 2K db. We purchased a SQL2k/JSP driven backend on which we extended their OM to meet our needs. It was build as an extranet product but ran very poorly across the 'Net.
    The biggest annoyance was not the actual transaction time of the app but the time it took from the end user to click a button and the start of the transaction.
    After much testing I determined it was the JSP.
    So what we have done to alieviate the issue is to have multiple regional Tomcats that 'throw' their transactions to a central colocation where the SQL servers sit (so the tomcats do the JSP managment in a sense locally to the end user) . For big clients we actually place a linux/tomcat box at the edge of their firewall. For whatever reason, I'm far too busy to determine the how now that I get the responses I need, this has completely eradicated the annoying pause between user interaction and the actual transaction to the DB server. Extended testing showed the SQL server running in the sub half second range to process a command but the tomcat rendering could take up to 2 to 5 seconds in worst case for no discernable reason. Moving the tomcat frontends to the network segment where the clients we solved it.
    Of course I'm digging into swing now too and it has some slowness that the Eclipse zealots say SWT fixes but I haven't the depth or experience to properly judge the camps arguments yet.
    hth...

  • Database access through Beans

    My question is about high level design. I've written some JSP pages and some very simple JavaBeans that work on Tomcat.
    Now I'm trying to design a Database access layer
    I want to have a connection pool class and some other business logic classes communicating with each other.
    How can I start a bean and keep it running and how do I access its methods from other beans?
    Is this even feasible?
    if I declare the scope of the bean as the application would I have to put it in all the pages of the web site or not?
    Also, should I just forget about JavaBeans and do Servlets? Maybe EJB is better for this?
    Please provide some examples in your answer if possible.
    Thanks,
    David A

    My question is about high level design. I've written
    some JSP pages and some very simple JavaBeans that
    work on Tomcat.
    Now I'm trying to design a Database access layerThe design and implementation of a persistence layer has nothing at to do with how the data is eventually displayed. Persistence is the same whether you use a Web or a Swing interface, so the question about Tomcat is moot.
    I'd look at Martin Fowler's "Patterns of Enterprise Application Architecture" for its chapter on persistence or the Hibernate object/relational mapping tool.
    I want to have a connection pool class and some other
    business logic classes communicating with each other.Personally, I prefer to let Tomcat handle the database connection pool. I use the Commons DBCP class and configure my connections that way. Then I have my Java code do a JNDI lookup to access them, do the required database operation, and then close the connection to return it to the pool.
    How can I start a bean and keep it running and how do I access its methods from other beans?
    Is this even feasible? I'm not sure I know what you mean by "start a bean and keep it running". HTTP is a request/response, stateless protocol. You should think about operations as being initiated by a request and then going out of scope once the response is generated, much like the protocol itself. You don't keep a bean running in that case.
    if I declare the scope of the bean as the application would I have to put it in all the pages of the web
    site or not?You have to <jsp:useBean> in every page that needs it. Whether or not application scope is really appropriate or necessary is another matter.
    Also, should I just forget about JavaBeans and do Servlets? You can and should use JSP for View, a servlet as your front controller, and JavaBeans to do the work in the back. It's not an either/or question. You really should be using all three.
    Maybe EJB is better for this?You use EJBs if you have a highly transactional, distributed, clustered application. If none of those things apply to you, there's no reason why you must use EJBs.
    Have a look at the Struts and Spring frameworks.

  • DB access in JSP ignored

    <p>Hi everybody</p><p>I created a report in Eclipse against a local MySQL, embedded it in a JSP and deployed it on a local Tomcat for testing. Evrything went smooth but when I reasign an identical remote DB to the report, copy the Web Archive onto a remote JBoss, the DB connection fails (MySQL 1045). </p><p>I assumed that the DB URL is kept inside the report (.rpt) file and that username and password have to be set in the JSP like so:</p><p>         IConnectionInfo connInfo1 = new ConnectionInfo();<br />        connInfo1.setUserName(Utilities.DB_USER);<br />        connInfo1.setPassword(Utilities.DB_PASSOWRD);<br />        connInfos.add(connInfo1);</p><p>       [...]<br />          //Create Viewer<br />        CrystalReportViewer viewer = new CrystalReportViewer();<br />        viewer.setReportSource(reportSource);<br />        viewer.setEnableLogonPrompt(false);  <br />        viewer.setDatabaseLogonInfos(connInfos);</p><p>If I use the remote DB from the local Tomcat it works too.<br /></p><p>Any help is highly appreciated.</p><p>Thanks in advance and regards from Zurich, Switzerland</p><p>Peter </p>

    <p>ok, I found a code snippet that allows to change database access from within a JSP page:<br /></p><p>        //Create Report<br />        ReportClientDocument reportClientDoc = new ReportClientDocument();<br />        String report = gerlingUser.getReportName();<br />        reportClientDoc.open(report, 0);<br />        reportSource = reportClientDoc.getReportSource();<br />        session.setAttribute("reportSource", reportSource);<br />        <br />        <br />        // ****** BEGIN CHANGE DATASOURCE SNIPPET ****************  <br />            {<br />                String connectString = "jdbc:mysql://192.168.1.11:3306/DBNAME";<br />                String driverName = "com.mysql.jdbc.Driver";<br />                String JNDIName = "nameDS";<br />                String userName = "username";<br />                String password = "userpassword";            <br />                // Switch all tables on the main report and sub reports<br />                JRCHelperSample.changeDataSource(reportClientDoc, userName, password, connectString, driverName, JNDIName);<br />            }<br />            // ****** END CHANGE DATASOURCE SNIPPET ****************     <br />        <br /><br /></p>

  • MIcrosoft Access in JSP

    Hi,
    I would like to use as demo version, a JSP page which can connect on Access DB.
    Is there some good tutorial how to do it thru JSP ?
    thanks a lot,
    Maileen

    Hi,
    I would like to use as demo version, a JSP page which
    can connect on Access DB.
    Is there some good tutorial how to do it thru JSP ?
    thanks a lot,
    MaileenThere are tutorials to show how to connect to a database, including Access. JSP is immaterial, since JSP is supposed to be a view technology.
    Figure out how to do it with a POJO and then have your JSP simply call it.
    If you're asking how to set up a JNDI connection pool (an excellent idea), that's specific to the servlet/JSP engine you deploy your JSP to. Tomcat has docs - check them out.
    %

  • ODBC database access

    Can we access a 'remote' ODBC compliant database through a JSP page being served
    by Weblogic? I know that the bridge cannot be used as it is not threadsafe but
    has that changed or is there any other way?
    Also, can we link in libraries within Weblogic.
    Thanks

    Hi Sash,
    There are definitely some other options.
    Did you already test the SequeLink type 3 driver?
    The pure java SequeLink JDBC driver uses the proprietary optimised SequeLink
    middleware protocol to communicate with a server component.
    The SequeLink ODBC Socket server (one of the possible server components)
    then uses ODBC API calls to communicate with an ODBC driver.
    This JDBC driver is thread safe, so you don't have to worry about that.
    A free eval and more info is available at
    http://www.merant.com/products/datadirect/jdbc/sequelink/overview.asp.
    Cheers,
    Dimitri
    "Sash" <[email protected]> wrote in message
    news:3b6071a5$[email protected]..
    >
    Can we access a 'remote' ODBC compliant database through a JSP page beingserved
    by Weblogic? I know that the bridge cannot be used as it is not threadsafebut
    has that changed or is there any other way?
    Also, can we link in libraries within Weblogic.
    Thanks

Maybe you are looking for

  • Movie Rental Period

    Can someone please help me understand Apple's seemingly draconian policy of allowing me only 24 hours to watch a rented movie? Why is it that the movie can sit on my iPod for 30 days unwatched, but as soon as I begin watching it, it is going to disap

  • Photoshop Elements 8 Editor will not open

    I'm running Windows Vista (Home Premium) on a Sony vaio laptop that exceeds (by a landslide) all of the requirements to operate Adobe Photoshop Elements 8.  The organizer opens just fine and functions properly.  When I try to open the editor (either

  • Is there a scroll box option in Captivate 7?

    I would like to a small text box (10% of the screen) on one of my slides that contains a lot of text.  I would like the user to be able to scroll through the text and for only three or four lines to be visible at a time.  Any ideas? Thank you in adva

  • Mail crash now won't launch

    I was opening a Mail attachment (a PowerPoint file from a trusted source) last night when my BlackBook suddenly restarted itself for no reason. I happen to think that fact is coincidental to the problem, but at least it gives some background. After a

  • Can we import a timestamp column in DIAdem

    I have a 2 channels with time information - one in string format and the other in timestamp format.  It seems that when I try to open my TDM file, DIAdem gets stuck.  I'm sure that its because I can't have string or timestamp information in a TDM fil