Results 1 to 12 of 12
  1. #1
    daisy is offline Member
    Join Date
    Mar 2011
    Posts
    12
    Rep Power
    0

    Default problem with JSP file

    hi...actually this is my first trial with java...i have created a JSP file like below. anyone can help me to correct the code? actually i want to store the data to database but when i click the submit button nothing happend

    <%@ page import="java.util.Date,java.text.DateFormat,java.t ext.SimpleDateFormat"%>
    <%@ page import="java.sql.*" %>
    <%@ page import="java.io.*" %>
    <%
    DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    Date date = new Date();

    %>

    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <title>Page Insert</title>
    </head>

    <body>
    <form action="index.jsp" method="post" enctype="multipart/form-data">
    <table width="361" border="2" align="center">

    <tr>
    <th scope="row">TRANSACTION</th>

    <td><input type="text" name="transaction" readonly="true" value="<%=dateFormat.format(date)%>">
    </tr>
    <tr>
    <th scope="row">VALID START </th>
    <td><select name="start" size="1" >
    <option>equal</option>
    <option>before</option>
    <option>after</option>
    <option>meet</option>
    <option>met_by</option>
    </select>
    <input type="text" name="textfield" size="15">
    </tr>
    <tr>
    <th scope="row">VALID END </th>
    <td><select name="end" size="1" id="end">
    <option>equal</option>
    <option>before</option>
    <option>after</option>
    <option>meet</option>
    <option>met_by</option>
    </select>
    <input type="text" name="textfieldd" size="15">
    </tr>
    <tr><th scope="row">Upload</th>
    <td><input name="file" type="file"></td></tr>

    </table>

    <p align="center">
    <input type="submit" name="Submit" value="Submit">
    <input type="reset" name="Reset" value="Reset">
    </p>
    </form>

    <% //obtain parameter from the client
    String transaction=request.getParameter("transaction");
    String start=request.getParameter("start");
    String textfield=request.getParameter("textfield");
    String end=request.getParameter("end");
    String textfieldd=request.getParameter("textfieldd");

    //to get the content type information from JSP Request Header
    String contentType = request.getContentType();
    //here we are checking the content type is not equal to Null and as well as the passed data from mulitpart/form-data is greater than or equal to 0
    if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
    DataInputStream in = new DataInputStream(request.getInputStream());

    //we are taking the length of Content type data
    int formDataLength = request.getContentLength();
    byte dataBytes[] = new byte[formDataLength];
    int byteRead = 0;
    int totalBytesRead = 0;
    //this loop converting the uploaded file into byte code
    while (totalBytesRead < formDataLength) {
    byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
    totalBytesRead += byteRead;
    }

    String file = new String(dataBytes);
    //for saving the file name
    String saveFile = file.substring(file.indexOf("filename=\"") + 10);
    saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
    saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
    int lastIndex = contentType.lastIndexOf("=");
    String boundary = contentType.substring(lastIndex + 1,contentType.length());
    int pos;
    //extracting the index of file
    pos = file.indexOf("filename=\"");
    pos = file.indexOf("\n", pos) + 1;
    pos = file.indexOf("\n", pos) + 1;
    pos = file.indexOf("\n", pos) + 1;
    int boundaryLocation = file.indexOf(boundary, pos) - 4;
    int startPos = ((file.substring(0, pos)).getBytes()).length;
    int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

    // creating a new file with the same name and writing the content in new file
    String folder = "C:/Users/dr saiful/My Documents/NetBeansProjects/sumayyah/web/";
    FileOutputStream fileOut = new FileOutputStream(folder+saveFile);
    fileOut.write(dataBytes, startPos, (endPos - startPos));
    fileOut.flush();
    fileOut.close();
    }

    %>



    <%
    String connectionURL = "jdbc:mysql://localhost:3306/test";
    PreparedStatement pstatement = null;
    Connection connection = null;
    Class.forName("com.mysql.jdbc.Driver").newInstance ();
    int updateQuery = 0;

    // check if the text box is empty
    if(transaction!=null && start!=null && textfield!=null&& end!=null&& textfieldd!=null){
    // check if the text box having only blank spaces
    if(transaction!="" && start!="" && textfield!="" && end!="" &&textfieldd!="") {
    try{
    connection = DriverManager.getConnection
    (connectionURL, "root","farham");

    // sql query to insert values in the secified table.
    String queryString = "INSERT INTO mysqltemp(transactionDate,operator1,validStart,ope rator2,validEnd) VALUES (?,?,?,?,?)";
    /* createStatement() is used for create statement
    object that is used for
    sending sql statements to the specified database. */
    pstatement = connection.prepareStatement(queryString);
    pstatement.setString(1, transaction);
    pstatement.setString(2, start);
    pstatement.setString(3, textfield);
    pstatement.setString(4, end);
    pstatement.setString(5, textfieldd);
    pstatement.executeUpdate();
    updateQuery = pstatement.executeUpdate();
    if (updateQuery != 0) { %>

    <br>
    <table>
    <tr><th>Data is inserted successfully
    in database</th></tr>
    </table>
    <%
    }
    }
    catch (Exception ex) {
    out.println("Unable to connect to database.");

    }
    finally {
    // close all the connections.
    pstatement.close();
    connection.close();
    }
    }
    }
    %>

    </body>
    </html>

  2. #2
    Petr's Avatar
    Petr is offline Senior Member
    Join Date
    Jan 2011
    Location
    Russia
    Posts
    620
    Rep Power
    4

    Default

    Hi. What is it in log file your service?
    Skype: petrarsentev
    http://TrackStudio.com

  3. #3
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,085
    Rep Power
    20

    Default

    1. Please use code tags when posting code. Unformatted code is hard to read.
    2. Almost all the code in there should be in its own classes called from a servlet. A JSP should be for displaying data, not processing it.
    3. As Petr asks, what is in your log files? I suspect there's an error somewhere.
    4. If there is an error, your exception handling is not going to tell you much. You should at least have an ex.printStackTrace() in that catch block.
    5. Why are you calling executeUpdate() twice?

  4. #4
    daisy is offline Member
    Join Date
    Mar 2011
    Posts
    12
    Rep Power
    0

    Default

    i'm still new with java:D actually i don't know what is log file..sorry for my weaknesses but i want to learn.hmm for my previous post,i already can settle it a little bit.i know where the mistakes when upload file,i need to use third party library.my problem now,i want to store path file with filename to database but failure to do that.

    Java Code:
    <%@ page import="java.sql.*"%>
    <%@ page import="java.io.File"%>
     <%@ page import="org.apache.commons.fileupload.*"%>
     <%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
     <%@ page import="org.apache.commons.io.*"%>
     <%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
     <%@ page import="org.apache.commons.fileupload.FileUploadException"%>
      <%@ page import="java.util.List"%>
     <%@ page import="java.util.Iterator"%>
            <center><h1>Your  Profile has been Uploaded</h1></center>
       <%!
         String temp_transaction="";
    	 String temp_start="";
    	 String temp_textfield="";
         String temp_end="";
    	 String temp_textfieldd="";
    	 int count1=0,count2=0,count3=0,count4=0,count5=0;
     %>
     <%
     boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    
    String folder="C:/Users/dr saiful/My Documents/NetBeansProjects/sumayyah/web/multimedia_data/";
     if (!isMultipart) {
     } else {
       FileItemFactory factory = new DiskFileItemFactory();
       ServletFileUpload upload = new ServletFileUpload(factory);
       List items = null;
       try {
       items = upload.parseRequest(request);
       } catch (FileUploadException e) {
       e.printStackTrace();
       }
       Iterator itr = items.iterator();
       while (itr.hasNext())
    	   {
       FileItem item = (FileItem) itr.next();
       if (item.isFormField())
    	   {
    	      String name = item.getFieldName();
    		  String value = item.getString();
    		  if(name.equals("transaction"))
    	           {
    			   temp_transaction=value;
    
    			   }
    			  if(name.equals("start"))
    	                  {
    				         temp_start=value;
    
    					  }
    			  if(name.equals("textfield"))
    	                  {
    				         temp_textfield=value;
    
    					  }
    			  if(name.equals("end"))
    	                  {
    			         temp_end=value;
    
    					  }
    
    			  if(name.equals("textfieldd"))
    	             {
    
    				  temp_textfieldd=value;
    				 }
    
       } else
    	   {
        try {
    
       String itemName = item.getName();
       File saveFile=new File(folder+itemName);
       item.write(saveFile);
    
    
       } catch (Exception e) {
       e.printStackTrace();
       }
       }
       }
       }
       %>
       <%
       Connection connection = null;
    String connectionURL = "jdbc:mysql://localhost:3306/test";
    
    PreparedStatement pstatement = null;
    
    
    try{
     Class.forName("com.mysql.jdbc.Driver").newInstance();
     connection = DriverManager.getConnection(connectionURL, "root","farham");
     
    File database_file = new File (folder);
    
    String queryString = "INSERT INTO mysqltemp(transactionDate,operator1,validStart,operator2,validEnd,file_path) VALUES (?,?,?,?,?,?)";
    
                  pstatement = connection.prepareStatement(queryString);
                  pstatement.setString(1, temp_transaction);
                  pstatement.setString(2, temp_start);
                  pstatement.setString(3, temp_textfield);
                  pstatement.setString(4, temp_end);
                  pstatement.setString(5, temp_textfieldd);
                  pstatement.setString(6, database_file.getName());
                  int s=pstatement.executeUpdate();
    
    if(s>0) {
    out.println("Uploaded successfully !");
    }
    else{
    out.println("unsucessfull to upload file.");
    }
    
    
    }
    catch(Exception e){e.printStackTrace();}
    
    %>

  5. #5
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,085
    Rep Power
    20

    Default

    Quote Originally Posted by daisy View Post
    ...i want to store path file with filename to database but failure to do that.
    That doesn't really tell us much.
    How does it fail?
    Exceptions?
    Stack traces?

  6. #6
    daisy is offline Member
    Join Date
    Mar 2011
    Posts
    12
    Rep Power
    0

    Default

    for example,when i fill up the form and upload one image file,let say name 'smile.jpg'.The image file is uploaded into multimedia_data folder.When I checked database,all the data inserted to table's field but for file_path field it just saved "C:/Users/dr saiful/My Documents/NetBeansProjects/sumayyah/web/multimedia_data/"
    I think it should save "C:/Users/dr saiful/My Documents/NetBeansProjects/sumayyah/web/multimedia_data/smile.jpg" right?
    Thank you Tolls

  7. #7
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,085
    Rep Power
    20

    Default

    It would be a lot easier to read if you'd written this in a servlet.
    Sticking code like that into a JSP is not good practice at all.

    What is the value of database_file.getName()?
    I can't see what database_file is.

  8. #8
    daisy is offline Member
    Join Date
    Mar 2011
    Posts
    12
    Rep Power
    0

    Default

    Hi there
    I have changed database_file.getName() to database_file.getPath()
    and I get the result as C:/Users/dr saiful/My Documents/NetBeansProjects/sumayyah/web/multimedia_data
    Actually, I can upload file to directory but I am wondering why I can't get the filename to store with file path

  9. #9
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,085
    Rep Power
    20

    Default

    Java Code:
    File database_file = new File (folder);
    You're only using the folder name there, so getPath() will only ever return the folder path.

  10. #10
    daisy is offline Member
    Join Date
    Mar 2011
    Posts
    12
    Rep Power
    0

    Default

    Thanks Tolls.

    i try with File database_file=new File (saveFile) but getting error. Let me find the solution first..i will inform here when i can trace the mistake
    thank guys

  11. #11
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,085
    Rep Power
    20

    Default

    I just realised I only replied on here (a month late) because someone (now removed) spammed this thread...

  12. #12
    daisy is offline Member
    Join Date
    Mar 2011
    Posts
    12
    Rep Power
    0

    Default Re: problem with JSP file

    <%@ page import="java.sql.*"%>
    <%@ page import="java.io.File"%>
    <%@ page import="org.apache.commons.fileupload.*"%>
    <%@ page import="org.apache.commons.fileupload.servlet.Serv letFileUpload"%>
    <%@ page import="org.apache.commons.io.*"%>
    <%@ page import="org.apache.commons.fileupload.disk.DiskFil eItemFactory"%>
    <%@ page import="org.apache.commons.fileupload.FileUploadEx ception"%>
    <%@ page import="java.util.List"%>
    <%@ page import="java.util.Iterator"%>

    <%!
    String temp_transaction="";
    String temp_start="";
    String temp_textfield="";
    String temp_end="";
    String temp_textfieldd="";
    %>

    <%
    //check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    //create a factory for disk-based file items
    FileItemFactory filefactory = new DiskFileItemFactory();
    //create a new file upload handler
    ServletFileUpload serFileUpload = new ServletFileUpload(filefactory);

    //try{
    //parse the request
    List fileItems = serFileUpload.parseRequest(request);
    //process the upload items
    Iterator iter = fileItems.iterator();
    while (iter.hasNext())
    {
    FileItem item = (FileItem) iter.next();
    if (item.isFormField())
    {
    String name=item.getFieldName();
    String value=item.getString();

    if(name.equals("transaction"))
    {temp_transaction=value;
    }
    if(name.equals("start"))
    {temp_start=value;
    }
    if(name.equals("textfield"))
    {temp_textfield=value;
    }
    if(name.equals("end"))
    {temp_end=value;
    }
    if(name.equals("textfieldd"))
    {temp_textfieldd=value;
    }
    }else{
    /* try{*/

    String itemName = item.getName();
    String folder="C:/Users/dr saiful/My Documents/NetBeansProjects/master_temporal/web/data/"+itemName;

    File saveFile=new File(folder);
    item.write(saveFile);
    /*}catch(Exception e1){
    e1.printStackTrace();
    }
    }
    }*/
    //}catch (FileUploadException e){
    //e.printStackTrace();
    //}

    Connection connection = null;
    String connectionURL = "jdbc:mysql://localhost:3306/test";
    PreparedStatement pstatement = null;

    //try{
    Class.forName("com.mysql.jdbc.Driver").newInstance ();
    connection = DriverManager.getConnection(connectionURL, "root","farham");

    //File file=new File();

    String queryString = "INSERT INTO mysqltemp(transactionDate,operator1,validStart,ope rator2,validEnd,file_path) VALUES (?,?,?,?,?,?)";

    pstatement = connection.prepareStatement(queryString);
    pstatement.setString(1, temp_transaction);
    pstatement.setString(2, temp_start);
    pstatement.setString(3, temp_textfield);
    pstatement.setString(4, temp_end);
    pstatement.setString(5, temp_textfieldd);
    pstatement.setString(6, itemName);
    int s=pstatement.executeUpdate();

    if(s>0) {
    out.println("Uploaded successfully !");
    }
    else{
    out.println("unsucessfull to upload file.");
    }
    }
    }


    //}
    //catch(Exception e){e.printStackTrace();}

    %>
    problem settle :)

Similar Threads

  1. Serious Jar-file problem
    By Igbear in forum Advanced Java
    Replies: 12
    Last Post: 04-27-2011, 10:08 PM
  2. .BAT File problem
    By egbert95 in forum New To Java
    Replies: 8
    Last Post: 08-03-2010, 01:26 AM
  3. jar file problem
    By nishant.4545 in forum New To Java
    Replies: 1
    Last Post: 07-03-2009, 08:36 PM
  4. problem with jar file
    By biba84 in forum Advanced Java
    Replies: 7
    Last Post: 11-09-2008, 06:46 PM
  5. problem - using a jar file
    By jon80 in forum New To Java
    Replies: 6
    Last Post: 07-07-2008, 07:49 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •