JSP Database access - Urgent

Hi,
A simple data access program to set values in a db. I have the following problems.
1. When I dont use if(request.getParameter("name")!=null) or any other parameter for testing null values, a row of null values is inserted each time I enter the jsp file.
2. One more problem is that the update is not regular. It sometimes works fine, someother times it fails miserably. It seems that the connection is not closed properly as I receive such a message when I try to shut dwon oracle.
3. A much more peculiar problem, when i paste a url directly into my browser, it runs fine, but not with location.href or a flash link!! eg the register.jsp file is reported as a nonexisting file (HTTP 404) when I provide a link to it from flash in the form http://localhost:8080/reg/register.jsp but when i type this url directly it works fine.
My code for register.jsp is:
<%@ page import="java.io.*,java.lang.*,java.sql.*,java.util.*"%>
<%
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:yogaesh","scott","tiger");
Statement stmt=con.createStatement();
if(request.getParameter("name")!=null)
String str="insert into rt values('" + request.getParameter("name") + "','" + request.getParameter("uname") + "','" + request.getParameter("pass") + "','" + request.getParameter("cpass") + "'," + request.getParameter("age") + ",'" + request.getParameter("sex") + "','" + request.getParameter("add") + "'," + request.getParameter("code") + ",'" + request.getParameter("ugqual") + "'," + request.getParameter("per") + ",'" + request.getParameter("iadd") +"')";
stmt.executeUpdate(str);
stmt.close();
con.commit();
con.close();
con=null;
str=null;
}catch(Exception e){out.println("Database error!!");}
%>
Please help me out and thanks in advance...
R. Yogaesh.

Hi,
A simple data access program to set values in a db. I
have the following problems.
1. When I dont use
if(request.getParameter("name")!=null) or any other
parameter for testing null values, a row of null
values is inserted each time I enter the jsp file. *********
* Yup. Use .equals("") or .equals("null") as tests, depends on your servlet container
2. One more problem is that the update is not regular.
It sometimes works fine, someother times it fails
miserably. It seems that the connection is not closed
properly as I receive such a message when I try to
shut dwon oracle. *************************
Use this:
Connection conn = null;
try{
   //Do database stuff
} catch {
   // Report your errors
} finally{
   try{
     if(conn!= null){
        conn.close();
     }catch{}
3. A much more peculiar problem, when i paste a url
directly into my browser, it runs fine, but not with
location.href or a flash link!! eg the register.jsp
file is reported as a nonexisting file (HTTP 404) when
I provide a link to it from flash in the form
http://localhost:8080/reg/register.jsp but when i type
this url directly it works fine.***********************
Maybe your flash is on another computer/server? Try using the link http://<ip address>:8080/reg/register.jsp or http://<dns name>:8080/reg/register.jsp
My code for register.jsp is:
<%@ page
import="java.io.*,java.lang.*,java.sql.*,java.util.*"%>
<%
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:yogaesh","sc
tt","tiger");
Statement stmt=con.createStatement();
if(request.getParameter("name")!=null)
String str="insert into rt values('" +
request.getParameter("name") + "','" +
request.getParameter("uname") + "','" +
request.getParameter("pass") + "','" +
request.getParameter("cpass") + "'," +
request.getParameter("age") + ",'" +
request.getParameter("sex") + "','" +
request.getParameter("add") + "'," +
request.getParameter("code") + ",'" +
request.getParameter("ugqual") + "'," +
request.getParameter("per") + ",'" +
request.getParameter("iadd") +"')";
stmt.executeUpdate(str);
stmt.close();
con.commit();
con.close();
con=null;
str=null;
}catch(Exception e){out.println("Database error!!");}
%>
Please help me out and thanks in advance...
R. Yogaesh.

Similar Messages

  • 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 Database Access : 500 Internal Server Error

    Hello everybody!
    My JSP code run until I write the next:
    Class.forName("com.ms.jdbc.odbc.JdbcOdbcDriver").newInstance();
    Connection connDB = DriverManager.getConnection("jdbc:odbc:OracleDB", "carlos_prb", "carlos_prb");
    Statement smentDB = connDB.createStatement();
    ResultSet rsDB = smentDB.executeQuery("SELECT * FROM websites");
    rsDB.close();
    smentDB.close();
    connDB.close();
    I need to access an Oracle Database. This code run in a java class, but not here. If I try to display the portlet the next message appears:
    Error: The listener returned the following Message: 500 Internal Server Error
    Somebody can help me, please?
    null

    Hi Charles,
    Thank you for yout help. I tried change this jar file for old one from
    jdeveloper 9 RC, but problem is still the same.
    I reviewed bcj4html.jar file too, and I did not discover problems in RequestParameters class.
    Have you any idea how to solve it ? I am sure that in project properties "libraries" I have selected
    all possible BC4J classes. (installation of DS and 9i database has made week before on new XP)
    Thank you very much for more info :)
    Ivo

  • JSP database access application code

    Does anyone know of existing sample code, that can be downloaded, for the above that can do the following:
    1. User login
    2. Data retrieval from database
    3. Data submission by fill in form
    Any help appreciated?
    Rupert

    Here's an ad-hoc example:
    <%
    final String PREPARED_STATEMENT = "SELECT * FROM userTable WHERE userid = ? AND userpwd = ?";
    String name = "", pwd = "", errorMsg = "",
    loginsubmitted = request.getParameter("loginsubmitted"),
    intendedPath = request.getParameter("intendedPath");
    //If the intendedPath was never set then set it to your 1st protected page...
    if(null == intendedPath)
       intendedPath = "your/protected/Page.jsp";
    if(null != loginsubmitted && "true".equals(loginsubmitted))
       name = request.getParameter("name");
       pwd = request.getParameter("pwd");
       //Code to be abstracted into a servlet of some sort...
       java.sql.Connection con = dataSource.getConnection(); //Assume dataSource has been initialized elsewhere
       java.sql.PreparedStatement stmnt = con.prepareStatement(PREPARE_STATEMENT);
       stmnt.setString(1,name);
       stmnt.setString(2,pwd);
       java.sql.ResultSet rs = stmnt.executeQuery();
       rs.next();
       if(rs.isAfterLast())
          errorMsg = "Invalid user ID or password.";
       else
          request.getRequestDispatcher(intendedPath).forward(request,respone);
    %>
    <h1>Login</h1>
    <form name="login" action="thispage.jsp" method="POST">
       Name: <input type="text" name="name" value="<%=name%>"/>
       Password: <input type="password" name="pwd" value="<%=pwd%>"/>
       <input type="hidden" name="loginsubmitted" value="true"/>
       <input type="hidden" name="intendedPath" value="<%=intendedPath%>"/>
       <input type="submit"/>
       <hr/>
       <h3><%=errorMsg%></h3>
    </form>Cliff

  • 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

  • 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

  • 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 using HTML, JSP, JavaBean, & Access

    I am trying to create an HTML page that a user logs into and can choose to query, add, delete or modify a specified database. I have created the HTML, the JSP, and access database but I can't figure out how to have 4 different JSP pages(one for each option) to get information from one JavaBean. PLEASE HELP

    http://swforum.sun.com/jive/thread.jspa?threadID=53106&tstart=0

  • 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);

  • How to connect jsp & ms-access

    hi,
    i need to retrive data from database.how to connect jsp & ms-access.i m using weblogic8.1.

    hi,
    i need to retrive data from database.how to connect jsp & ms-access.i m using weblogic8.1.

  • 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 delays-how to improve upon that?

    Hi friends,
    I have this simple class,which takes in query and returns the results.I don't know why the database access is so slow,and if i try to add my driver load statements into the constructor the java class starts throwing "null pointer exception"(Java Class code given below)..I don't know much about connection pool,can u just have a look at this simple class,and tell me if there's anything on which i can improve upon and where to add the(*.close() statements).The same query runs instantly if i make a php program.Urgent help needed...please help me guys.
    public class getResultSet{  private Connection con = null;  private Statement st = null;  private String dsn = "jdbc    b2j:net:xxx";  private String uname = "xxx";  private String pwd = "xxx";  private String query = "";  ResultSet results;   public void ResultS()throws Exception{      try{          Class.forName("com.ibm.db2.jcc.DB2Driver");          con = DriverManager.getConnection(dsn, uname, pwd);          st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,                                   ResultSet.CONCUR_READ_ONLY);         }      catch (SQLException e) {          e.printStackTrace();          }     }     public ResultSet getResults(String query){            results = null;            try{               results = st.executeQuery(query);               }               catch(SQLException sqle){                 sqle.printStackTrace();               }            return results;     }   }

    Some comments on the code
    public class getResultSet{ // Class names should start with a capital letter and be nouns
    private Connection con = null;
    private Statement st = null; // Statements are transient and should probably not be a member variable
    private String dsn = "jdbc    b2j:net:xxx";  // dsn, user, pass should be final
    private String uname = "xxx"; 
    private String pwd = "xxx"; 
    private String query = "";  // Seems you're not using this
    ResultSet results;   // This really shouldn't be declared here
    public void ResultS()throws Exception{ // Method should start with a lower-case letter and be a verb/* The client code is supposed to call this, then the other method?
    Very fragile. I'm guessing NullPointerExceptions occur if ResultS
    is not called first. Have the other method call this one as necessary.
    try{        
    Class.forName("com.ibm.db2.jcc.DB2Driver");
    con = DriverManager.getConnection(dsn, uname,
    uname, pwd);
    st =
    st =
    =
    con.createStatementResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_READ_ONLY);
    ultSet.CONCUR_READ_ONLY);
    catch (SQLException e) {  
    e.printStackTrace();
    public ResultSet getResults(String query){      
    results = null;
    try{          
    results = st.executeQuery(query);
    catch(SQLException sqle){   
    sqle.printStackTrace();
    return results; // It's a bad idea to return ResultSets as that leaves resources open
    } // Where's the cleanup? You're leaving ResultSet, Statement, Connection open
    >It is probably slow because opening connections takes a long time. You may or may not need a connection pool depending on your app. Perhaps you can just open a connection at the beginning and leave it open until your app finishes. That should reduce the overhead and still be very simple.

  • 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.

  • Error: EncryptedLocalStore database access error in AIR 3.4

    Hi,
    A few of our users were prompted to update to Adobe AIR 3.4 today. After doing this they were no longer able to use our Adobe AIR "desktop" app. I've downloaded the 3.4 SDK and run our app via ADT and I get the following error in the Introspector:
    Error: EncryptedLocalStore database access error
    Our app stores configuration info in the EncryptedLocalStore.
    This has never occurred before and if I uninstall 3.4 and go back to 3.3 the problem does not exist.  We need an urgent solution to this because we have hundreds of users who use our AIR app every day. We've told them NOT to update to 3.4 until further notice.
    Any assistance would be greatly appreciated.
    Brad.

    Hello AIR developers,
    I want to thank you for your patience and again apologize to you for catching you off guard with this change.  Our team met today and our immediate plan is to roll the ELS changes back to the AIR 3.3 level. We are working on a timeline for when this update will be occur.  We are treating this with the highest priority and expect it will not take long.
    For those interested, here’s how and why this change occurred.  Over the past year or two we’ve heard complaints about the reliability of our ELS implementation, especially on the Mac platform. We’ve known all along that we wanted to refactor this feature and remove dependence on third party libraries.  We undertook this restructuring during the 3.4 release schedule and finished without hearing any major complaints from our internal or prerelease users.  One assumption we made was that ELS data was treated like a volatile cache.  In the past we’ve given guidance on the usage of ELS in both blogs and our help documentation, suggesting that developers should not depend on ELS as permanent data storage because it “can be lost for a variety of reasons”. Our position on this hasn’t changed, but we acknowledge and understand that some applications have come to depend on this data and if at all possible, we should do our best to persist it.
    Going forward, we will most likely reimplement our changes from 3.4, however when doing this we will also work to provide a way to automatically upgrade and persist your application's data.  We will also give plenty of advanced notice and make releases available on our labs.adobe.com site.  We want this change to improve your lives by adding improved stability and we look forward to working with you on this in the future.
    Thanks,
    Chris

Maybe you are looking for

  • Any body who can solve it

    1).I want to call oracle graphics app. from oracle forms6. 2).Same as above with parameters. Thanx in advance!

  • Objects and text cannot be moved from top left

    I just merged my website from some other drag and drop editor to DW. I am determined to learn how to work everything (Or at least enough to get by). But I have hit a snag along my learning path, and am hoping it is something simple. I am trying to ad

  • Changes made in EMS are not reflected in EMC

    Hello all, I realise that this is 2013 discussion, but I could not find a 2010 section. My problem is simple: any change that I make inside the Exchange Shell is simply not reflected in the Console. It doesn't appear there. It can't be searched for.

  • [SOLVED]Cannot Connect to Wireless Network during Installation

    (Sorry, yet another newbie unable to configure a network connection properly) I've been using Ubuntu for a little while now (since 11.10), and finally decided to give Arch a try (for a number of reasons). I thought I was comfortable enough with the C

  • I believe creating a clipping mask is the answer, but im doing something wrong

    This is a hard one to describe so i attached this link: file:///C:/Users/Marcus/Documents/Wacom%20work/zang-deli.jpg. Im trying to make the object (the black bit) consist of the image in the background so instead of being black it will be multicolour