Here is my Code index.jsp
<%--
Document : index
Created on : 14 Feb, 2012, 4:46:05 AM
Author : Sanjib Narzary
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="/CBKD_WEB/img" method="post"
enctype="multipart/form-data"
name="productForm" id="productForm"><br><br>
<table width="400px" align="center" border=0
style="background-color:ffeeff;">
<tr>
<td align="center" colspan=2 style=" font-weight:bold;font-size:20pt;">
Image Details
</td>
</tr>
<tr>
<td align="center" colspan=2> </td>
</tr>
<tr>
<td>Image Link: </td>
<td>
<input type="file" name="file" id="file">
<td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="Submit" value="Submit"></td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
</table>
</form>
</body>
</html>
and Servlet img.java
import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
//import org.apache.commons.fileupload.*;
public class img extends HttpServlet {
#Override
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
boolean isMultipart = ServletFileUpload.isMultipartContent(
request);
System.out.println("request: " + request);
if (!isMultipart) {
System.out.println("File Not Uploaded");
} else {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException ex) {
Logger.getLogger(img.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("items: " + items);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
String name = item.getFieldName();
System.out.println("name: " + name);
String value = item.getString();
System.out.println("value: " + value);
} else {
try {
String itemName = item.getName();
Random generator = new Random();
int r = Math.abs(generator.nextInt());
String reg = "[.*]";
String replacingtext = "";
System.out.println("Text before replacing is:-"
+ itemName);
Pattern pattern = Pattern.compile(reg);
Matcher matcher = pattern.matcher(itemName);
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(buffer, replacingtext);
}
int IndexOf = itemName.indexOf(".");
String domainName = itemName.substring(IndexOf);
System.out.println("domainName: " + domainName);
String finalimage = buffer.toString() + "_" + r + domainName;
System.out.println("Final Image===" + finalimage);
File savedFile = new File("E:/sanjib/" + "temp/" + finalimage);
item.write(savedFile);
out.println("<html>");
out.println("<body>");
out.println("<table><tr><td>");
out.println("<img src=images/" + finalimage + ">");
out.println("</td></tr></table>");
out.println("</body>");
out.println("</html>");
} catch (Exception e) {
}
}
}
}
}
}
This code is fine and working without any error in Netbeans Web Application with Glassfish 3.1 Server. But what my problem is if i try to upload the image it is showing Alert in Firefox like The connection to the server was reset while the page was loading and in Google Chrome This Error
This web page is not available
The connection to localhost was interrupted.
Here are some suggestions:
Reload this web page later.
Check your Internet connection. Reboot any routers, modems or other network devices that you may be using.
Add Google Chrome as a permitted programme in your firewall or antivirus software's settings. If it is already a permitted programme, try deleting it from the list of permitted programmes and adding it again.
If you use a proxy server, check your proxy settings or contact your network administrator to make sure that the proxy server is working. If you don't believe you should be using a proxy server, adjust your proxy settings: Go to the spanner menu > Options > Under the Bonnet > Change proxy settings... > LAN Settings and deselect the "Use a proxy server for your LAN" checkbox.
Error 101 (net::ERR_CONNECTION_RESET): The connection was reset.
Related
I need help in checking the data into the database before insertion.
Issue:
I have used the general method to insert the values into database.But I need to include this condition into my servlet code i.e if a data is already present in the database,then that data should not be inserted into the database and the remaining data should be inserted into the database.While doing this no alert should be raised to the user.
This is my code.
products.jsp
<%#page import="java.util.List"%>
<%#page import="web.Products"%>
<%#page import="java.util.ArrayList"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<form method="post" action="Save_Products">
<b>
Brand Name:<font color="green">
<% String brand_name=(String)session.getAttribute("brand_name");
out.print(brand_name);%>
<c:set var="brand_name" value="brand_name" scope="session" />
</font></b>
<table>
<tr>
<th> Products</th>
<th> Description </th>
</tr>
<tr>
<td> <b><%
List<Products> pdts = (List<Products>) request.getAttribute("list");
if(pdts!=null){
for(Products prod: pdts){
out.println("<input type=\"checkbox\" name=\"prod\" value=\"" + prod.getProductname() + "\">" + prod.getProductname()+"<br>");
} %> </b></td>
<td><%for(Products prod: pdts){
out.println("<input type=\"text\" name=\"desc\" style=\"width:50px; height:22px\"/><br/>");
}
}
%> </td>
</tr>
<br/>
<br/>
<tr><td align="center"> <input type="submit" value="Save" name="save"/> </td></tr>
</table>
</form>
</body>
</html>
Servlet code
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;
public class Save_Products extends HttpServlet {
static final String dbURL = "jdbc:mysql://localhost:3306/pdt";
static final String dbUser = "root";
static final String dbPass = "root";
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ResultSet rs=null;
Connection connection = null;
try{
HttpSession session = request.getSession();
String brand_name =(String) session.getAttribute("brand_name");
String [] prod_list = request.getParameterValues("prod");
String [] desc_list = request.getParameterValues("desc");
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection (dbURL,dbUser,dbPass);
String sql="insert into pdt_list(brand_name,product_name,desc)values(?,?,?)";
PreparedStatement prep = connection.prepareStatement(sql);
int num_values = Math.min(prod_list.size(), desc_list.size());
int count_updated = 0;
for(int i = 0; i < num_values; i++){
prep.setString(1, brand_name);
prep.setString(2, prod_list[i]);
prep.setString(3,desc_list[i]);
count_updated += prep.executeUpdate();
}
if(count_updated>0)
{
out.print("Products Saved Successfully...");
RequestDispatcher rd=request.getRequestDispatcher("Save_Success.jsp");
rd.forward(request,response);
}
else{
RequestDispatcher rd=request.getRequestDispatcher("Save_Failure.jsp");
rd.forward(request,response);
}
prep.close();
}
catch(Exception E){
//Any Exceptions will be caught here
System.out.println("The error is"+E.getMessage());
}
finally {
try {
connection.close();
}
catch (Exception ex) {
System.out.println("The error is"+ex.getMessage());
}
}
}
}
I am still wondering what it is that i am doing wrong,my problem is i dont know if it is my entire sample code which has na error or my connection to the database which has an issues, as of where i stand i am not sure what is making me get this error. (displayed below).I have tried to look here at stack overflow but all i get is loading images using JSP but not adding them to the database. If we have one i couldnt trace please help me with the link. I have included all the libraries needed and my code has no error apart from this output. I came here because i am stranded and need a short review of what you proffesionals think is wrong with my code as done below. I will really appreciate anyhelp given as i am working on a deadline.
my Database name is
AppDB
I was wondering should i use the name of the table? to INSERT INTO? which is
'contacts'
Error Message
HTTP Status 404 - /UploadImageOnWeb/uploadServlet type Status report
message /UploadImageOnWeb/uploadServlet description The requested
resource is not available. Apache Tomcat/8.0.23
Thank you
Java Servlet Code
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
/**
* Servlet implementation class FileUploadDBServlet
*/
#MultipartConfig(maxFileSize = 16177215)
#WebServlet("/FileUploadDBServlet")
public class FileUploadDBServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
// database connection settings
/*private String dbURL = "jdbc:mysql://localhost/AppDB";
private String dbUser = "root";
private String dbPass = "mypassword";*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
InputStream inputStream = null;
Part filePart = request.getPart("photo");
if (filePart != null) {
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
inputStream = filePart.getInputStream();
}
Connection conn = null;
String message = null;
try {
// connects to the database
/*DriverManager.registerDriver("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);*/
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/AppDB","root","mypassword");
// constructs SQL statement
String sql = "INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, firstName);
statement.setString(2, lastName);
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBlob(3, inputStream);
}
int row = statement.executeUpdate();
if (row > 0) {
message = "File uploaded and saved into database";
}
} catch (SQLException ex) {
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// sets the message in request scope
request.setAttribute("Message", message);
// forwards to the message page
getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
}
}
}
My .Jsp class
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File Upload to Database Demo</title>
</head>
<body>
<center>
<h1>File Upload to Database Demo</h1>
<form method="post" action="uploadServlet" enctype="multipart/form-data">
<table border="0">
<tr>
<td>Enter First Name: </td>
<td><input type="text" name="firstName" size="20"/></td>
</tr>
<tr>
<td>Enter Last Name: </td>
<td><input type="text" name="lastName" size="20"/></td>
</tr>
<tr>
<td>Portrait Photo: </td>
<td><input type="file" name="photo" size="20"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save">
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
Display Jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Message</title>
</head>
<body>
<center>
<h3><%=request.getAttribute("Message")%></h3>
</center>
</body>
</html>
The 404 error indicates that the form is not even getting to the servlet.
You defined the action attribute in the form as uploadServlet which doesn't seem to be a valid URL for your application.
The servlet's URL is defined in the #WebServlet annotation as FileUploadDBServlet.
So you can fix it by changing the action in the form or changing the URL for the servlet.
Here is my index.html:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="extra/js/jquery-1.10.2.min.js"></script>
<script src="extra/downloads/dropzone.js"></script>
<script>
$(document).ready(function()
{
var myDropzone = new Dropzone("div#my-awesome-dropzone", {url:'UploadServlet'});
Dropzone.autoDiscover = false;
myDropzone.on("addedfile", function(file) {
// Create the remove button
var removeButton = Dropzone.createElement("<button>Remove file</button>");
// Capture the Dropzone instance as closure.
var _this = this;
// Listen to the click event
removeButton.addEventListener("click", function(e) {
// Make sure the button click doesn't submit the form:
e.preventDefault();
e.stopPropagation();
// Remove the file preview.
_this.removeFile(file);
// If you want to the delete the file on the server as well,
// you can do the AJAX request here.
});
// Add the button to the file preview element.
file.previewElement.appendChild(removeButton);
});
$("#button").click(function(){
var source = $("#my-awesome-dropzone").attr("src");
alert(source);
});
});
</script>
<link rel="stylesheet" href="extra/downloads/css/dropzone.css" type="text/css">
<title>Insert title here</title>
</head>
<body>
<form action="UploadServlet" method="post" enctype="multipart/form-data" >
<table id="table">
<tr>
<td> Unique ID : </td>
<td><input type="text" id="unique" name="unique" maxlength="6" required></input></td>
</tr>
<tr>
<td> Name : </td>
<td><input type="text" id="fullname" name="fullname" maxlength="255" required></input></td>
</tr>
<tr>
<td> Age : </td>
<td><input type="text" id="age" name="age" maxlength="255" required></input></td>
</tr>
<tr>
<td> Address : </td>
<td><input type="text" id="address" name="address" maxlength="255" required></input></td>
</tr>
<tr>
<td> Phone_number </td>
<td><input type="text" id="phonenumber" name="phonenumber" maxlength="10" required></input></td>
</tr>
</table>
<div id="my-awesome-dropzone" class="dropzone"></div>
<div>
<input type="submit" value="Submit data and files!"></input>
</div>
</form>
</body>
</html>
And this my servlet:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dropzone;
import java.io.File;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.html.HTMLDocument.Iterator;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import com.oreilly.servlet.multipart.MultipartParser;
import com.oreilly.servlet.multipart.Part;
import com.oreilly.servlet.multipart.FilePart;
public class UploadServlet extends HttpServlet {
private String fileSavePath;
private static final String UPLOAD_DIRECTORY = "upload";
public void init() {
fileSavePath = getServletContext().getRealPath("/") + File.separator + UPLOAD_DIRECTORY;/*save uploaded files to a 'Upload' directory in the web app*/
if (!(new File(fileSavePath)).exists()) {
(new File(fileSavePath)).mkdir(); // creates the directory if it does not exist
}
}
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
Connection con = null;
List<FileItem> items;
try {
items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
// ... (do your job here)
} else {
// Process form file field (input type="file").
String fieldname = item.getFieldName();
String filename = FilenameUtils.getName(item.getName());
InputStream filecontent = item.getInputStream();
// ... (do your job here)
}
}
} catch (FileUploadException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
/*
String uid = request.getParameter("unique");
String fullname = request.getParameter("fullname");
System.out.println(fullname);
String age = request.getParameter("age");
String address = request.getParameter("address");
String phonenumber = request.getParameter("phonenumber");*/
String path = null;
String message = null;
String resp = "";
int i = 1;
resp += "<br>Here is information about uploaded files.<br>";
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dropzone", "root", "root");
String sql = "INSERT INTO details(u_id,name,age,address,phonenumber,path) values(?,?,?,?,?,?)";
PreparedStatement statement = con.prepareStatement(sql);
//##########################################################?//
MultipartParser parser = new MultipartParser(request, 1024 * 1024 * 1024); /* file limit size of 1GB*/
Part _part;
while ((_part = parser.readNextPart()) != null) {
if (_part.isFile()) {
FilePart fPart = (FilePart) _part; // get some info about the file
String name = fPart.getFileName();
if (name != null) {
long fileSize = fPart.writeTo(new File(fileSavePath));
resp += i++ + ". " + fPart.getFilePath() + "[" + fileSize / 1024 + " KB]<br>";
} else {
resp = "<br>The user did not upload a file for this part.";
}
}
}// end while
//##################################################################//
statement.setString(1,"uid");
statement.setString(2,"fullname");
statement.setString(3,"age");
statement.setString(4,"address");
statement.setString(5,"phonenumber");
statement.setString(6,"path");
int row = statement.executeUpdate();
if(row>0){
message = "Contact saved";
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message = "ERROR: " +e.getMessage();
}
finally
{
if(con !=null)
{
try{
con.close();
}
catch(SQLException ex)
{
ex.printStackTrace();
}
}
System.out.println(message);
request.setAttribute("Message",message);
getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
}
}
}
Here is screenshot of the error:
I want to use the dropzone for uploading images.But if I use multipart/form-data for the form, the fields except the images give null values. I tried using the simple getParameter method. But it doesnt seem to work. Also I tried using Lists but it gives an error. Anyone tried dropzone with jsp?? Help
This is happening because you are not treating the whole form as dropzone but you are treating only the #my-awesome-dropzone div as dropzone .That won't work if you want to submit whole form with the files on one click.
1)In the form tag add an id say id="mydropzone" and class class="dropzone"
<form action="UploadServlet" id="mydropzone" class="dropzone" method="post" enctype="multipart/form-data" >
2)Remove the div from your code which has the id id="my-awesome-dropzone".Then Add a new div to show the files uploaded in drag and drop
<div id="dropzonePreview"></div>
3)add an id to your submit button
<input type="submit" id="sbmtbtn" value="Submit data and files!" />
4)now add this script
<script>
Dropzone.options.mydropzone = {
// url does not has to be written if we have wrote action in the form tag but i have mentioned here just for convenience sake
addRemoveLinks: true,
autoProcessQueue: false, // this is important as you dont want form to be submitted unless you have clicked the submit button
autoDiscover: false,
paramName: 'pic', // this is similar to giving name to the input type file like <input type="file" name="pic" />
previewsContainer: '#dropzonePreview', // we specify on which div id we must show the files
clickable: false, // this tells that the dropzone will not be clickable . we have to do it because v dont want the whole form to be clickable
accept: function(file, done) {
console.log("uploaded");
done();
},
error: function(file, msg){
alert(msg);
},
init: function() {
var myDropzone = this;
//now we will submit the form when the button is clicked
document.getElementById("sbmtbtn").onclick = function(e) {
e.preventDefault(); //this will prevent the default behaviour of submit button because we want dropzone to submit the form
myDropzone.processQueue(); // this will submit your form to the specified action which directs to your jsp upload code
// after this, your whole form will get submitted with all the inputs + your files and the jsp code will remain as usual
//REMEMBER you DON'T have to call ajax or anything by yourself to submit the inputs, dropzone will take care of that
};
} // init end
};
</script>
NOTE :
YOU DO NOT have to write any extra code to make the form submit .
After writing the above code just follow your normal flow to upload
file in jsp like writing the xml and writing the servlet class and fetch all the inputs and files there.
Remember dropzone uses ajax to upload so the form will not be
refreshed when you click submit.
You cannot click on the form to upload files now you have to just
drag the files in the form.
i tried to make this work .
But still give me error
I still new in this
My .jsp file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Staff Page - Add Book</title>
</head>
<body>
<center>
<h2 style="text-align: center;">Return Book Form.</h2>
<form name="uForm" method="get" action="addbookServlet" enctype="multipart/form-data">
<table align="center" width="300px" style="background-color:#f5f5f5;border:1px solid #e5e5e5; padding:5px;">
<tr><td colspan=2 align="center" height="10px"></td></tr>
<tr>
<td><b>Book ID</b></td>
<td><input type="text" name="book_id" size="50"></td>
</tr>
<tr>
<td><b>Book Title</b></td>
<td><input type="text" name="book_title" size="50"></td>
</tr>
<tr>
<td><b>Book Author</b></td>
<td><input type="text" name="book_author" size="50"></td>
</tr>
<tr>
<td><b>Book Quantity</b></td>
<td><input type="text" name="book_quantity" size="50"></td>
</tr>
<tr>
<td><b>Book Location</b></td>
<td><input type="text" name="book_location" size="50"></td>
</tr>
<tr>
<td><b>Book Image</b></td>
<td><input type="file" name="book_image" accept="image/x-png, image/gif, image/jpeg" size="50"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" class="g-button" value="Submit"></td>
</tr>
<tr><td colspan=2 align="center" height="10px"></td></tr>
</table>
</form>
</center>
</body>
</html>
My .java file
package caal;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import caal.DbConnection.*;
public class AddBook extends HttpServlet {
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//response.setContentType("text/html");
// PrintWriter out = response.getWriter();
Connection con = null; // connection to the database
String message = null; // message will be sent back to client
// Statement stmt;
String book_id = request.getParameter("book_id");
String book_title = request.getParameter("book_title");
String book_author = request.getParameter("book_author");
String book_quantity = request.getParameter("book_quantity");
String book_location = request.getParameter("book_location");
//String book_image = request.getParameter("book_image");
InputStream inputStream = null; // input stream of the upload file
// obtains the upload file part in this multipart request
Part filePart = request.getPart("book_image");
if (filePart != null) {
// prints out some information for debugging
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
// obtains input stream of the upload file
inputStream = filePart.getInputStream();
}
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
con = DbConnection.getConn();
String query = "INSERT INTO booktable(bookId, bookTitle, bookAuthor, bookQuantity, bookLocation, bookimage) VALUES (?,?,?,?,?,?)";
System.out.println("query " + query);
PreparedStatement statement = con.prepareStatement(query);
statement.setString(1, book_id);
statement.setString(2, book_title);
statement.setString(3, book_author);
statement.setString(4, book_quantity);
statement.setString(5, book_location);
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBlob(6, inputStream);
}
//stmt = con.createStatement();
//stmt.executeUpdate(query);
response.sendRedirect("login.jsp");
con.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
// closes the database connection
try {
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// sets the message in request scope
request.setAttribute("Message", message);
// forwards to the message page
getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
}
}
}
My web.xml become error . if i put like this
<!-- SERVLET FOR ADD BOOK -->
<servlet>
<servlet-name>addBookServlet</servlet-name>
<servlet-class>caal.AddBook</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>addBookServlet</servlet-name>
<url-pattern>/addbookServlet</url-pattern>
</servlet-mapping>
<multipart-config>
<location>/tmp</location>
<max-file-size>20848820</max-file-size>
<max-request-size>418018841</max-request-size>
<file-size-threshold>1048576</file-size-threshold>
</multipart-config>
The error is
Error occurred during deployment: Exception while deploying the app [fpx] : org.xml.sax.SAXParseException; lineNumber: 52; columnNumber: 23; Deployment descriptor file WEB-INF/web.xml in archive [web]. cvc-complex-type.2.4.a: Invalid content was found starting with element 'multipart-config'. One of '{"http://java.sun.com/xml/ns/j2ee":description, "http://java.sun.com/xml/ns/j2ee":display-name, "http://java.sun.com/xml/ns/j2ee":icon, "http://java.sun.com/xml/ns/j2ee":distributable, "http://java.sun.com/xml/ns/j2ee":context-param, "http://java.sun.com/xml/ns/j2ee":filter, "http://java.sun.com/xml/ns/j2ee":filter-mapping, "http://java.sun.com/xml/ns/j2ee":listener, "http://java.sun.com/xml/ns/j2ee":servlet, "http://java.sun.com/xml/ns/j2ee":servlet-mapping, "http://java.sun.com/xml/ns/j2ee":session-config, "http://java.sun.com/xml/ns/j2ee":mime-mapping, "http://java.sun.com/xml/ns/j2ee":welcome-file-list, "http://java.sun.com/xml/ns/j2ee":error-page, "http://java.sun.com/xml/ns/j2ee":jsp-config, "http://java.sun.com/xml/ns/j2ee":security-constraint, "http://java.sun.com/xml/ns/j2ee":login-config, "http://java.sun.com/xml/ns/j2ee":security-role, "http://java.sun.com/xml/ns/j2ee":env-entry, "http://java.sun.com/xml/ns/j2ee":ejb-ref, "http://java.sun.com/xml/ns/j2ee":ejb-local-ref, "http://java.sun.com/xml/ns/j2ee":service-ref, "http://java.sun.com/xml/ns/j2ee":resource-ref, "http://java.sun.com/xml/ns/j2ee":resource-env-ref, "http://java.sun.com/xml/ns/j2ee":message-destination-ref, "http://java.sun.com/xml/ns/j2ee":message-destination, "http://java.sun.com/xml/ns/j2ee":locale-encoding-mapping-list}' is expected.. Please see server.log for more details.
I also have try using #MultipartConfig but it still not working . I need some help .
In web.xml, you must have correct and corresponding DOCTYPE and DTD/XSD setting, otherwise you may get xml invalidation error.
Try check your web.xml XSD setting refer here and try again.
The XSD version is preferred since JSP 2.0 / Servlets 2.4 (eg: Tomcat 5.5). Note that the XML encoding can be specified as ISO-8859-1, UTF-8, or any other valid encoding in either version, and should match the actual encoding of your text file.
I have problem with get a value from combobox in my .jsp file to servlet.
I use method request.getParameter i other servlets and it works. In this class it don't.
I was also trying to get value from text field to this servlet but also don't work. I don't have any idea how to solve this problem.
I have combobox like that:
<form action="upload" method="POST" enctype="multipart/form-data">
<p class="folders_save">Folder:
<select name="folders1" id="user">
<%
user = (User)session.getAttribute("user");
listOfFolders = user.listOfFolders();
if(listOfFolders != null){
for(File file : listOfFolders){
out.print("<option value="+file.getName()+">"+file.getName()+"</option>");
}
}
%>
</select>
</p>
<input class="pole" type="file" name="file" />
<input class="wrzuc" type="submit" value="Wrzuc!">
</form>
I'm tring to get value:
String folder = request.getParameter("folders1");
My jsp file
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org /TR/html4/loose.dtd">
<html>
<head>
<%# page import="tools.User" %>
<%# page import="java.io.File" %>
<%# page import="java.text.DecimalFormat" %>
<%#page language="Java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="style.css" />
<title>Serwer dysku sieciowego </title>
</head>
<body>
<div class="container">
<div class="ramka_zaproszenie">
<%
File[] listOfFolders;
User user;
String username;
String status = null;
if(session.getAttribute("user")!=null){
user = (User)session.getAttribute("user");
username = user.getLogin();
status = user.getType().toString();
} else {
username = "unknown";
}
%>
<p class="loguj">Witaj, <%= username %>!</p><br>
<% if(session.getAttribute("user")!=null){ %>
<p class="tekst">Wrzuc plik na serwer:</p>
<form action="upload" method="POST" enctype="multipart/form-data">
<p class="folders_save">Folder:
<select name="folders1" id="user">
<%
user = (User)session.getAttribute("user");
listOfFolders = user.listOfFolders();
if(listOfFolders != null){
for(File file : listOfFolders){
out.print("<option value="+file.getName()+">"+file.getName()+"</option>");
}
}
%>
</select>
</p>
<input class="pole" type="file" name="file" />
<input class="wrzuc" type="submit" value="Wrzuc!">
</form>
<form action="folder" method="get">
<p class="tekst"> Folder: <br><input class="pole" id="Folder" type="text" name="folderName" />
<br /></p>
<input class="zatwierdz" type="submit" id="submit" value="Utwórz" /><br>
</form>
<br />
<% if(status.equalsIgnoreCase("ADMIN")){ %>
<a class="wroc" href="zmiana_rozmiaru.jsp">Zmiana Pojemnosci</a>
<%}%>
<br />
<br />
<p class="tekst">Posiadane pliki na serwerze:</p>
<form method="post">
Folder:
<select name="folders">
<option value=0 selected="selected" >Wybierz folder</option>
<%
user = (User)session.getAttribute("user");
listOfFolders = user.listOfFolders();
if(listOfFolders != null){
for(File file : listOfFolders){
out.print("<option value="+file.getName()+">"+file.getName()+"</option>");
}
}
%>
</select>
<input type="submit" value="Wybierz"><br>
</form>
<br />
Pliki z folderu: <%=request.getParameter("folders")%>
<center><table id="tabela">
<tr class="alt">
<th>Nazwa</th>
<th>Rozmiar</th>
<th>Pobierz</th>
<th>Usun</th>
</tr>
<%
System.out.println(request.getParameter("folders"));
user = (User)session.getAttribute("user");
File[] listOfFiles = user.listOfFiles(request.getParameter("folders"));
if(listOfFiles != null){
for(File file : listOfFiles){
DecimalFormat twoDForm = new DecimalFormat("#.##");
out.print("<tr class=\"alt\"><td>" + file.getName()+"</td><td>" +twoDForm.format((double)file.length()/1024.0)+" KB</td><td align=center> <img border=\"0\" src=\"downloadsmall.png\"></td><td align=center><a src=\"deletesmall.png\" href=\"delete?filePath="+file.getAbsolutePath()+"\" ><img border=\"0\" src=\"deletesmall.png\"></a></td></tr>");
}
}
%>
</table>
</center><br>
<form action="logout" method="post">
<input type="image" src="wylacznik.png" id="submit">
</form>
<br><br>
<%
if (session.getAttribute("warning") != null) {
%>
<span><%= session.getAttribute("warning") %></span>
<%
session.removeAttribute("warning");
}
%>
<% } %>
<div class="footer">Copyright 2013 by JavaProjectTeam.</div>
</div>
</div>
</body>
</html>
And my servlet file
<pre>package servlets;
import java.io.*;
import java.sql.SQLException;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.annotation.WebServlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import java.sql.Connection;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import tools.Connector;
import tools.User;
#WebServlet("/upload")
public class UploadServlet extends HttpServlet {
private boolean isMultipart;
private String filePath;
private File file ;
public void init(){
// Get the file location where it would be stored.
filePath = getServletContext().getInitParameter("file-upload");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
// Check that we have a file upload request
request.setCharacterEncoding("UTF-8");
String folder = request.getParameter("folders1");
HttpSession session = request.getSession(true);
User user = (User)session.getAttribute("user");
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
if( !isMultipart ){
session.setAttribute("warning", "Nie masz zadnych plikow");
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location", "hello.jsp");
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax(user.getSpace() * 1024);
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fileName = fi.getName();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( filePath+"\\"+user.getId()+"\\"+folder+"\\"+
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( filePath+"\\"+user.getId()+"\\"+folder+"\\"+
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write(file);
System.out.println(file.getName());
try{
Connection connection = new Connector().getConnection();
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.GERMAN);
otherSymbols.setDecimalSeparator('.');
otherSymbols.setGroupingSeparator('.');
DecimalFormat twoDForm = new DecimalFormat("#.##", otherSymbols);
System.out.println(twoDForm.format((double)file.length()/1024.0));
connection.createStatement().executeUpdate("UPDATE `users` SET `space` = `space`-"+twoDForm.format((double)file.length()/1024.0)+" where id="+user.getId());
} catch(SQLException e){
e.printStackTrace();
}
session.setAttribute("warning", "Plik został dodany do wirtualnego dysku.");
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location", "hello.jsp");
}
}
out.println("</body>");
out.println("</html>");
}catch(Exception ex) {
System.out.println(ex);
session.setAttribute("warning", "File is too big! Only "+user.getSpace()+"KB left.");
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location", "hello.jsp");
}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
throw new ServletException("GET method used with " +
getClass( ).getName( )+": POST method required.");
}
}<code>
It's because you're sending a multipart/form-data request while that's by default not supported by servlets. I however notice that you're still using the "legacy" Apache Commons FileUpload to obtain the uploaded file instead of new Servlet 3.0 provided HttpServletRequest#getPart(). In that case, you've basically 2 options:
Stick to Commons FileUpload. You should be collecting regular form fields in the else block of your if (!fi.isFormField()) which you're currently completely ignoring.
if (!fi.isFormField()) {
// Collect uploaded file from fi.
} else {
// Collect normal form field from fi.
}
Get rid of Commons FileUpload and use #MultipartConfig annotation.
#WebServlet("/upload")
#MultipartConfig
public class UploadServlet extends HttpServlet {
This way you can get files by request.getPart() and keep using request.getParameter() the usual way for regular form fields.
See also:
How to upload files to server using JSP/Servlet?
Unrelared to the concrete problem, that's not a combobox, but that's a dropdown. A combobox is an editable dropdown. Further, writing Java code in JSP is a bad practice. Java code belongs in Java classes like a servlet. To loop over options, use JSTL <c:forEach>. And, writing HTML code in a Java class like a servlet is a bad practice. HTML code belongs in a JSP file. Use RequestDispatcher#forward() to present results in a JSP. See further also our servlets wiki page.
Oh, you've a major threadsafety problem in your servlet. There's only one instance of a servlet during applications lifetime which is shared across all HTTP requests. Those fields
private boolean isMultipart;
private String filePath;
private File file ;
would be shared across all HTTP requests resulting in potential major problems when multiple users concurrently use the same servlet at the same moment. Get rid of them and move them to inside the doXxx() method block.