index.jsp
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML5 drag'n'drop file upload with Servlet</title>
<script>
window.onload = function() {
var dropbox = document.getElementById("dropbox");
dropbox.addEventListener("dragenter", noop, false);
dropbox.addEventListener("dragexit", noop, false);
dropbox.addEventListener("dragover", noop, false);
dropbox.addEventListener("drop", dropUpload, false);
}
function noop(event) {
event.stopPropagation();
event.preventDefault();
}
function dropUpload(event) {
noop(event);
var files = event.dataTransfer.files;
for (var i = 0; i < files.length; i++) {
upload(files[i]);
}
}
function upload(file) {
document.getElementById("status").innerHTML = "Uploading " + file.name;
var formData = new FormData();
formData.append("file", file);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.open("POST", "uploadServlet", false); // If async=false, then you'll miss progress bar support.
xhr.send(formData);
}
function uploadProgress(event) {
// Note: doesn't work with async=false.
var progress = Math.round(event.loaded / event.total * 100);
document.getElementById("status").innerHTML = "Progress " + progress + "%";
}
function uploadComplete(event) {
document.getElementById("status").innerHTML = event.target.responseText;
}
</script>
<style>
#dropbox {
width: 300px;
height: 200px;
border: 1px solid gray;
border-radius: 5px;
padding: 5px;
color: gray;
}
</style>
</head>
<body>
<div id="dropbox">Drag and drop a file here...</div>
<div id="status"></div>
</body>
</html>
uploadServlet.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package officer;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class uploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
// Apache Commons-Fileupload library classes
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(factory);
if (! ServletFileUpload.isMultipartContent(request)) {
out.println("sorry. No file uploaded");
return;
}
else
{
// parse request
List items = sfu.parseRequest(request);
FileItem file = (FileItem) items.get(0);
String type=file.getContentType();
float size=file.getSize()/1024;
if((type.equals("image/jpeg"))&& ((size <201)&&(size>10)))
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "epolicia", "admin");
con.setAutoCommit(false);
PreparedStatement ps = con.prepareStatement("insert into image(image) values(?)");
ps.setBinaryStream(1, file.getInputStream(), (int) file.getSize());
ps.executeUpdate();
con.commit();
con.close();
out.println("Proto Added Successfully. <p> <a href='ListPhotoServlet'>List Photos </a>");
}
else
{
out.print("Invalid Image Selected !!");
}
}
}
catch(Exception ex) {
out.println( "Error --> " + ex.getMessage());
}
}
}
Above code is just simply inserting the image into database. But, i want to insert the image on the basis of userid. Then, what should i change in my code. Need help to pass the userid when image will be dropped into the box. Thanks in advance !!
I tested this in Chrome browser.
In your script;
formData.append("file", file);
// if userid is in your script
fd.append("userid", userid);
// or if userid is at server, then send it to browser first
// fd.append("userid", <%=userid%>);
In UploadServlet;
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
String userid = item.getString();
else //its the file
...
Related
I want a solution for my problem. I am facing a problem where the data received from Search.js form is not sending data to my Java Servlet in DYNAMIC WEB PROJECT in Eclipse. I have attached the screenshots and the codes also. Please help.
Search.js Code:
import React from 'react'
import axios from 'axios';
const Search = () => {
const handleSubmit = async (e) => {
const re = /^[0-9\b]+$/
if (e.key === "Enter") {
if(e.target.value==='' || re.test(e.target.value))
{
e.preventDefault()
let res= fetch("http://localhost:8080/Hrc/search",{
mode:"no-cors",
method:"POST",
headers: {
'Content-Type': 'application/json'
},
body:JSON.stringify({
cust_number:e.target.value
})})
console.log(e.target.value)
if(res.ok)
{
console.log("Successful search")
}
else{
console.log("Error")
}
}
// ... submit to API or something
}
}
return (
<div>
<div>
<form onSubmit='http://localhost:8080/Hrc/search' method="post">
<input type="text" name='cust_number' placeholder='Search Customer Id' className="sarch-button" onKeyPress={handleSubmit}/>
</form>
</div>
</div>
)
}
export default Search
App.js
import React,{ useState } from 'react'
import {useMemo} from 'react'
import Logo from './components/Logo.js'
import './App.css'
import PredictBtn from './components/PredictBtn.js'
import Analytics from './components/AnalyticsView.js'
import Advsrchmodal from './components/Advsrchmodal.js'
import Search from './components/Search.js'
import Add from './components/Addmodal.js'
import Edit from './components/Edit.js'
import Delete from './components/Delete.js'
import Table from './components/Table.js'
import table from './assets/json/mock.json'
import {Columns} from './components/column'
export default function App(){
const [advmodal,setadvmodal]=useState(false)
const [addmodal,setaddmodal]=useState(false)
const [editmodal,seteditmodal]=useState(false)
const [delmodal,setdelmodal]=useState(false)
const [search,setSearch]=useState('')
const searchItems=(searchValue)=>{
setSearch(searchValue)
}
const columns = useMemo(()=> Columns ,[])
const data = useMemo(()=> table, [])
return(
<div>
<body>
<Logo />
<div className='header-btns'>
<PredictBtn/><Analytics/>
<button onClick={()=> setadvmodal(true)} className="leftbtns adv-srch-btn"id="adv-srch-modal">ADVANCED SEARCH</button>
<Advsrchmodal onClose={()=> setadvmodal(false)} show={advmodal}/>
<Search handleSearch={searchItems}/>
<button onClick={()=> setaddmodal(true)} className="rightbtns add-btn" id ="add-modal">ADD</button>
<Add onClose={()=> setaddmodal(false)} show={addmodal}/>
<button onClick={()=> seteditmodal(true)} className="rightbtns edit-btn">EDIT</button>
<Edit onClose={()=> seteditmodal(false)} show={editmodal}/>
<button onClick={()=> setdelmodal(true)} className="rightbtns del-btn">DELETE</button>
<Delete onClose={()=>setdelmodal(false)} show={delmodal}/>
</div>
<div className="Table">
<Table columns={Columns} data={data}/>
</div>
</body>
</div>
)
}
Ignore the other imports , focus on the search import
Search.java('The Servlet') code:
package com.highradius;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.io.*;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.FileWriter;
#WebServlet("/servlet")
public class Search extends HttpServlet {
private static final long serialVersionUID = 1L;
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost:3306/grey_goose?zeroDateTimeBehavior=convertToNull";
static final String USER="root";
static final String PASSWORD="ROHITghosh1234";
public Search() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
resp.addHeader("Access-Control-Allow-Origin","http://localhost:3000");
Connection conn = null;
Statement stmt = null;
List<Response> demoList = new ArrayList<>();
String cust_number=req.getParameter("cust_number");
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
stmt = conn.createStatement();
String sql;
if(cust_number=="")
sql="select sl_no,business_code,cust_number,clear_date,buisness_year,doc_id,posting_date,document_create_date,due_in_date,invoice_currency,document_type,posting_id,total_open_amount,baseline_create_date,cust_payment_terms,invoice_id from winter_internship";
else
sql="select sl_no,business_code,cust_number,clear_date,buisness_year,doc_id,posting_date,document_create_date,due_in_date,invoice_currency,document_type,posting_id,total_open_amount,baseline_create_date,cust_payment_terms,invoice_id from winter_internship where cust_number like '"+cust_number+"%'";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()) {
Response res=new Response();
res.setsl_no(rs.getInt("sl_no"));
res.setbusiness_code(rs.getString("business_code"));
res.setcust_number(rs.getString("cust_number"));
res.setclear_date(rs.getDate("clear_date"));
res.setbuisness_year(rs.getInt("buisness_year"));
res.setdoc_id(rs.getString("doc_id"));
res.setposting_date(rs.getDate("posting_date"));
res.setdocument_create_date(rs.getDate("document_create_date"));
res.setdue_in_date(rs.getDate("due_in_date"));
res.setinvoice_currency(rs.getString("invoice_currency"));
res.setdocument_type(rs.getString("document_type"));
res.setposting_id(rs.getInt("posting_id"));
res.settotal_open_amount(rs.getDouble("total_open_amount"));
res.setbaseline_create_date(rs.getDate("baseline_create_date"));
res.setcust_payment_terms(rs.getString("cust_payment_terms"));
res.setinvoice_id(rs.getInt("invoice_id"));
demoList.add(res);
}
String jsonString = getJSONStringFromObject(demoList);
resp.setContentType("application/json");
try {
resp.getWriter().write(jsonString);
File files=new File("D:\\\\hrcsummerinternship\\\\src\\\\assets\\\\json\\\\searchoutput.json");
files.delete();
FileWriter file=new FileWriter("D:\\hrcsummerinternship\\src\\assets\\json\\searchoutput.json");
file.write(jsonString);
file.close();
} catch (IOException e) {
e.printStackTrace();
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
private String getJSONStringFromObject(List<Response> filmlist) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(filmlist);
//System.out.print(json);
return json;
}
}
Folder Structure
Console output
I have also used axios, but to no avail. Please Help
Building a web application where the user can search a word and a relevant image will be returned. But whenever the query is changed, the image does not. What is going on here?
User searches "cat" and image comes back. But then stays like this after the first query.
DefineWord.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="googleAPI.*" %>
<!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>Define</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" href="css/bootstrap-lightbox.min.css">
<link rel="stylesheet" href="css/bootstrap-lightbox.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/includeNAV.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<style>
.fit_image img {
max-width: 100%;
max-height: 100%;
}
.fit_image {
width: 400px;
height: 200px;
}
</style>
</head>
<body>
<div id="includedNav"></div>
<div class="container">
<form id="searchForm" method="get" action="LinkServlet">
<fieldset>
<input id="s" type="text" name="query" /> <input type="submit"
value="Submit" id="submitButton" />
</fieldset>
</form>
</div>
<br />
<!-- Requests attributes from servlet -->
<div class="container">
<%-- <%=request.getAttribute("links") %> --%>
<br /> ONE LINK:
<div class="fit_image">
<img src="<%=request.getAttribute("onelink")%>"/>
</div>
</div>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script
src="//blueimp.github.io/Gallery/js/jquery.blueimp-gallery.min.js"></script>
<script src="js/bootstrap-image-gallery.min.js"></script>
</body>
</html>
LinkServlet.java
package googleAPI;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/LinkServlet")
public class LinkServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LinkServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.removeAttribute("onelink");
// Get query from user through http parameter
String query = request.getParameter("query");
String results = google.psuedomain(query);
// Put results string into a ArrayList so that the jsp can dynamically
// call each image
String[] urlAry = results.split("\n");
ArrayList<String> ar = new ArrayList<String>();
ar.clear();
ar.removeAll(ar);
for (int i = 0; i < urlAry.length; i++) {
ar.add(urlAry[i]);
}
// Get first element from ArrayList and set attribute
String onelink = ar.get(0);
request.setAttribute("onelink", onelink);
// Set query results to attribute so JSP can call it
request.setAttribute("links", ar);
// Forward request back to the same JSP.
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/DefineWord.jsp");
dispatcher.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
google.java
package googleAPI;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Pattern;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
public class google {
static StringBuilder results = new StringBuilder();
static String finalResults;
public static String getFinalResults() {
return finalResults;
}
public static void setFinalResults(String finalResults) {
google.finalResults = finalResults;
}
public static String psuedomain(String qry) throws IOException {
String key = "*********private key************";
URL url = new URL("https://www.googleapis.com/customsearch/v1?key=" + key
+ "&cx=*********private key************&q=" + qry + "&alt=json");
// CONNECTION LOGIC
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
while ((output = br.readLine()) != null) {
Pattern pattern = Pattern.compile("(?:(?:https?)+\\:\\/\\/+[a-zA-Z0-9\\/\\._-]{1,})+(?:(?:jpe?g|png|gif))");
Matcher matcher = pattern.matcher(output);
if (matcher.find()) {
results.append(matcher.group() + "\n");
}
}
conn.disconnect();
finalResults = removeDup();
return finalResults;
}
public static String removeDup() {
String[] tokens = results.toString().split("\n");
StringBuilder resultBuilder = new StringBuilder();
Set<String> alreadyPresent = new HashSet<String>();
boolean first = true;
for (String token : tokens) {
if (!alreadyPresent.contains(token)) {
if (first)
first = false;
else
resultBuilder.append("\n");
if (!alreadyPresent.contains(token))
resultBuilder.append(token + "\n");
}
alreadyPresent.add(token);
}
String result = resultBuilder.toString();
return result;
}
}
Any ideas as to why this might be happening? Thanks for your time.
I think the problem had to do with using static methods. I removed the static declarations, changed some code around and it seems to work now.
google2.java
package googleAPI;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Pattern;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
public class google2 {
StringBuilder results = new StringBuilder();
String finalResults;
public String psuedomain(String qry) throws IOException {
String key = "*********private key************";
URL url = new URL("https://www.googleapis.com/customsearch/v1?key=" + key
+ "&cx=*********private key************&q=" + qry + "&alt=json");
// CONNECTION LOGIC
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
while ((output = br.readLine()) != null) {
Pattern pattern = Pattern.compile("(?:(?:https?)+\\:\\/\\/+[a-zA-Z0-9\\/\\._-]{1,})+(?:(?:jpe?g|png|gif))");
Matcher matcher = pattern.matcher(output);
if (matcher.find()) {
results.append(matcher.group() + "\n");
}
}
conn.disconnect();
finalResults = removeDup();
return finalResults;
}
public String removeDup() {
String[] tokens = results.toString().split("\n");
StringBuilder resultBuilder = new StringBuilder();
Set<String> alreadyPresent = new HashSet<String>();
boolean first = true;
for (String token : tokens) {
if (!alreadyPresent.contains(token)) {
if (first)
first = false;
else
resultBuilder.append("\n");
if (!alreadyPresent.contains(token))
resultBuilder.append(token + "\n");
}
alreadyPresent.add(token);
}
String result = resultBuilder.toString();
return result;
}
public String finalResults(String query){
try {
psuedomain(query);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return finalResults;
}
}
Link2Servlet.java
package googleAPI;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#SuppressWarnings("serial")
#WebServlet("/Link2Servlet")
public class Link2Servlet extends HttpServlet {
public Link2Servlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String query = request.getParameter("query");
google2 google = new google2();
String test = google.finalResults(query);
String[] urlAry = test.split("\n");
ArrayList<String> ar = new ArrayList<String>();
for (int i = 0; i < urlAry.length; i++) {
ar.add(urlAry[i]);
}
request.setAttribute("onelink", ar.get(0));
request.setAttribute("links", ar);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/DefineWord.jsp");
dispatcher.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
I am unable to upload file. There is no exception,no error but when the code is run, file doesn't uploaded. What could be the reason for it?
As debugged :
iterator.hasNext() returns false
`
<form action='UploadMatch' method='post' enctype="multipart/form-data">
<input type='file' />
<input type='submit' class='btn btn-default' id='uploadmatch' />upload
</form>
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package servlet;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
/**
*
* #author user
*/
public class UploadMatch extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain");
PrintWriter writer = response.getWriter();
String path = request.getParameter("Data");
try {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if( !isMultipart ) {
writer.println("File cannot be uploaded !");
} else {
DiskFileItemFactory diskFileItem = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(diskFileItem);
List list = null;
try {
list = fileUpload.parseRequest(request);
}catch(Exception exc) {
writer.println(exc);
}
Iterator iterator = list.iterator();
while(iterator.hasNext()) { // WHILE LOOP (DOESN'T ENTER)
FileItem fileItem = (FileItem)iterator.next();
if(fileItem.isFormField()) {
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
} else {
// Process form file field (input type="file").
String fieldName = fileItem.getFieldName();
String fileName = FilenameUtils.getName(fileItem.getName());
File file = new File(request.getServletContext().getContextPath(),fileName);
writer.println(">>>>>>>>>>W:/" + " " + fileName);
fileItem.write(file);
}
}
}
}catch(Exception exc) {
writer.println(exc);
}
}
}
Note : The code doesn't enter the while loop
I am getting null pointer exception here:
List fileItems = upload.parseRequest(req);
That happens if the number of line in the file is greater the 2000 approx, as I could upload the file of lines above 1000. Someone please help me out. The form is below.
<form name="fos_picks" id="fos_picks" action="<%=path%>/fos_upld" method="post" enctype="multipart/form-data" >
<br/><br/><br/><br/>
<p align="center">
<input type="file" name="file" size="50" /><br/>
<br/>
<input type="submit" class="buttons" value="Upload File" />
</p>
</form>
Upload controller code...
package file_proc;
import DBConn.DBConn;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.PreparedStatement;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
#WebServlet(name="file_upld", urlPatterns = {"/file_upld"})
public class file_upld extends HttpServlet {
private boolean isMultipart;
private String filePath;
private int maxFileSize = 50 * 1024;
private int maxMemSize = 10 * 1024;
private File file ;
/* public void init( ){
// Get the file location where it would be stored.
filePath =
getServletContext().getInitParameter("file-upload");
}*/
#Override
public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException, java.io.IOException {
// Check that we have a file upload request
java.io.PrintWriter out = res.getWriter( );
// out.println("entered");
isMultipart = ServletFileUpload.isMultipartContent(req);
res.setContentType("text/html");
if( !isMultipart ){
out.println("!multipart");
System.out.println("here");
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("c:/temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
ServletContext servletContext = getServletContext();
String path = servletContext.getRealPath("/");
BufferedReader br=null;
String fileName="";
DBConn db = new DBConn();
try{
// Parse the request to get file items.
System.out.println("here1"+req);
List fileItems = upload.parseRequest(req);
// Process the uploaded file items
Iterator i = fileItems.iterator();
/* out.println("<html>");
out.println("<head>");
out.println("<title>Upload</title>");
out.println("</head>");
out.println("<body>");*/
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( "c:/Temp/" +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( "c:/Temp/"+
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
if(!file.exists())
{
File fold=new File(file.getParent());
fold.mkdirs();
}
fi.write( file ) ;
System.out.println("Uploaded Filename: " + fileName + "<br>");
}
}
}catch(Exception ce)
{
out.println("<font size='30' color='red'>Error Code 016</font>");
//out.println("Exception1: "+ce);
}
//read uploaded file and insert into table********************************************
// String newline = System.getProperty("line.separator");
// File file = new File(path+"//"+fileName);
// file.createNewFile();
try{
if(file.isFile())
{
br = new BufferedReader(new FileReader(file));
String str="";
String temp[]=null;
file.canWrite();
file.canRead();
file.setWritable(true);
db.conn.setAutoCommit(false);
while((str=br.readLine())!=null)
{
temp=str.split(" ");
// PreparedStatement ps = db.conn.prepareStatement("INSERT INTO file_proc VALUES(?,?,?,?,?,?,?,?,?,STR_TO_DATE(?,'%m/%d/%Y'))");
PreparedStatement ps = db.conn.prepareStatement("INSERT INTO file_proc(run_date,zone,location,bank,file_type,num_rec,ex_sett_date,ex_stat_date) "
+ "VALUES(STR_TO_DATE(?,'%m/%d/%Y'),?,?,?,?,?,STR_TO_DATE(?,'%m/%d/%Y'),STR_TO_DATE(?,'%m/%d/%Y'))");
ps.setString(1,temp[0]);
ps.setString(2,temp[1]);
ps.setString(3,temp[2]);
ps.setString(4,temp[3]);
ps.setString(5,temp[4]);
ps.setInt(6,Integer.parseInt(temp[5]));
ps.setString(7,temp[6]);
ps.setString(8,temp[7]);
ps.executeUpdate();
ps.close();
}
db.conn.commit();
db.conn.setAutoCommit(true);
db.conn.close();
br.close();
file.delete();
// RequestDispatcher rd = req.getRequestDispatcher("./status/status.jsp");
// rd.forward(req, res);
out.print("success");
// out.println("</html>");
}
else
{
out.println(file+" is not a file");
}
}catch(Exception ex) {
out.println("file name= "+fileName);
// out.println("DBEX= "+ex );
out.println("<font size='30' color='red'>Error Code 017 - Recommended date format = m/d/yyyy.</font>");
out.println("<font size='30' color='red'>Check the column order</font>"+ex);
//file.delete();
// RequestDispatcher rd = req.getRequestDispatcher("./status/error.jsp");
// rd.forward(req, res);
}finally{
try{
db.conn.close();
br.close();
}catch(Exception e){}
}
}
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, java.io.IOException {
doPost(request, response);
}
}
**** Here is form ******
<form name="file_proc" id="file_proc" method = "post" action="../file_upld" enctype="multipart/form-data">
<br/><br/><br/><br/>
<p align="center">
<input type="file" id="file" name="file" size="50" /><br/>
<br/>
<input type="submit" class="buttons" value="Upload File" />br/><br/><br/>
</p>
</form>
Upload controller code...
package file_proc;
import DBConn.DBConn;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.PreparedStatement;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
#WebServlet(name="file_upld", urlPatterns = {"/file_upld"})
public class file_upld extends HttpServlet {
private boolean isMultipart;
private String filePath;
private int maxFileSize = 50 * 1024;
private int maxMemSize = 10 * 1024;
private File file ;
/* public void init( ){
// Get the file location where it would be stored.
filePath =
getServletContext().getInitParameter("file-upload");
}*/
#Override
public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException, java.io.IOException {
// Check that we have a file upload request
java.io.PrintWriter out = res.getWriter( );
// out.println("entered");
isMultipart = ServletFileUpload.isMultipartContent(req);
res.setContentType("text/html");
if( !isMultipart ){
out.println("!multipart");
System.out.println("here");
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("c:/temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
ServletContext servletContext = getServletContext();
String path = servletContext.getRealPath("/");
BufferedReader br=null;
String fileName="";
DBConn db = new DBConn();
try{
// Parse the request to get file items.
System.out.println("here1"+req);
List fileItems = upload.parseRequest(req);
// Process the uploaded file items
Iterator i = fileItems.iterator();
/* out.println("<html>");
out.println("<head>");
out.println("<title>Upload</title>");
out.println("</head>");
out.println("<body>");*/
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( "c:/Temp/" +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( "c:/Temp/"+
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
if(!file.exists())
{
File fold=new File(file.getParent());
fold.mkdirs();
}
fi.write( file ) ;
System.out.println("Uploaded Filename: " + fileName + "<br>");
}
}
}catch(Exception ce)
{
out.println("<font size='30' color='red'>Error Code 016</font>");
//out.println("Exception1: "+ce);
}
//read uploaded file and insert into table********************************************
// String newline = System.getProperty("line.separator");
// File file = new File(path+"//"+fileName);
// file.createNewFile();
try{
if(file.isFile())
{
br = new BufferedReader(new FileReader(file));
String str="";
String temp[]=null;
file.canWrite();
file.canRead();
file.setWritable(true);
db.conn.setAutoCommit(false);
while((str=br.readLine())!=null)
{
temp=str.split(" ");
// PreparedStatement ps = db.conn.prepareStatement("INSERT INTO file_proc VALUES(?,?,?,?,?,?,?,?,?,STR_TO_DATE(?,'%m/%d/%Y'))");
PreparedStatement ps = db.conn.prepareStatement("INSERT INTO file_proc(run_date,zone,location,bank,file_type,num_rec,ex_sett_date,ex_stat_date) "
+ "VALUES(STR_TO_DATE(?,'%m/%d/%Y'),?,?,?,?,?,STR_TO_DATE(?,'%m/%d/%Y'),STR_TO_DATE(?,'%m/%d/%Y'))");
ps.setString(1,temp[0]);
ps.setString(2,temp[1]);
ps.setString(3,temp[2]);
ps.setString(4,temp[3]);
ps.setString(5,temp[4]);
ps.setInt(6,Integer.parseInt(temp[5]));
ps.setString(7,temp[6]);
ps.setString(8,temp[7]);
ps.executeUpdate();
ps.close();
}
db.conn.commit();
db.conn.setAutoCommit(true);
db.conn.close();
br.close();
file.delete();
// RequestDispatcher rd = req.getRequestDispatcher("./status/status.jsp");
// rd.forward(req, res);
out.print("success");
// out.println("</html>");
}
else
{
out.println(file+" is not a file");
}
}catch(Exception ex) {
out.println("file name= "+fileName);
// out.println("DBEX= "+ex );
out.println("<font size='30' color='red'>Error Code 017 - Recommended date format = m/d/yyyy.</font>");
out.println("<font size='30' color='red'>Check the column order</font>"+ex);
//file.delete();
// RequestDispatcher rd = req.getRequestDispatcher("./status/error.jsp");
// rd.forward(req, res);
}finally{
try{
db.conn.close();
br.close();
}catch(Exception e){}
}
}
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, java.io.IOException {
doPost(request, response);
}
}
**** Here is form ******
<form name="file_proc" id="file_proc" method = "post" action="../file_upld" enctype="multipart/form-data">
<br/><br/><br/><br/>
<p align="center">
<input type="file" id="file" name="file" size="50" /><br/>
<br/>
<input type="submit" class="buttons" value="Upload File" />br/><br/><br/>
</p>
</form>
here is the log4j stuff, it shows the error at filter.java, which i am not using in the current servlet.
[ERROR] 29:05(file_upld.java:doPost:172) failed!
java.lang.NullPointerException at
file_proc.file_upld.doPost(file_upld.java:120) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:641) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:722) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at filter.filter.doFilter(filter.java:16) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
at
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Here goes the filter.javapackage filter;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
public class filter implements Filter{
private FilterConfig config=null;
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException
{
HttpServletResponse hsr = (HttpServletResponse) res;
hsr.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
hsr.setHeader("Pragma", "no-cache"); // HTTP 1.0.
hsr.setDateHeader("Expires", 0); // Proxies.
chain.doFilter(req, res);
}
#Override
public void destroy() { }
#Override
public void init(FilterConfig config) {
this.config = config;
}
}
Your concrete problem is caused by bad exception handling and tight-coupling view with the controller.
After filtering noise from your code, it goes roughly like:
File file = null;
try {
// ...
file = new File(...);
// ...
} catch (Exception e) {
out.println("...");
}
try {
if (file.isFile())
// ...
} else {
// ...
}
} catch (Exception e) {
out.println("...");
}
The NullPointerException is been thrown at the line with the if (file.isFile()) block. This thus means that the first try block threw an exception, hereby leaving the file as null.
The cause of the problem is two-fold:
The first try block is not returning from the servlet method on exception, but incorrectly continuing the code flow.
The second try block is not checking beforehand if the file is not null.
Your concrete problem is however much bigger. You're completely swallowing exceptions and printing irrelevant HTML code instead of throwing them through and/or logging the exceptions.
Replace your catch blocks as follows:
} catch (Exception e) {
throw new ServletException(e);
}
By default, this way the exception will be logged and be displayed in its full glory, complete with the stacktrace, in a HTTP 500 error page. The stacktrace gives you a wealth of information to understand the problem and fix it.
Unrelated to the concrete problem, there are many other conceptual and design mistakes in the code, but they are so far not directly related to the concrete problem. I would however recommend to take a pause and go through some sane Servlet books/tutorials/resources. This code seems to be just cobbled together based on snippets found in Google instead of being well thought out written. The first step would be understanding how servlets actually work: How do servlets work? Instantiation, sessions, shared variables and multithreading
I am using spring framework and i am having Index.jsp like :
Code:
<html>
<head></head>
<body>
<p>File Upload</p>
<form action="ImportService" enctype="multipart/form-data" method="POST">
<input type="file" name="file1"><br>
<input type="Submit" value="Upload File"><br>
</form>
</body>
I have ImportService as
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class ImportService extends HttpServlet {
private static final String TMP_DIR_PATH = "c:\\tmp";
private File tmpDir;
private static final String DESTINATION_DIR_PATH = "c:\\files";
private File destinationDir;
public void init(ServletConfig config) throws ServletException {
super.init(config);
tmpDir = new File(TMP_DIR_PATH);
if (!tmpDir.isDirectory()) {
throw new ServletException(TMP_DIR_PATH + " is not a directory");
}
// String realPath =
// getServletContext().getRealPath(DESTINATION_DIR_PATH);
destinationDir = new File(DESTINATION_DIR_PATH);
if (!destinationDir.isDirectory()) {
throw new ServletException(DESTINATION_DIR_PATH
+ " is not a directory");
}
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String name = "param";
String value = request.getParameter(name);
String welcomeMessage = "Welcome " + value;
System.out.println("Message=" + welcomeMessage);
response.setContentType("text/html");
response.setContentType("text/plain");
System.out.println("Inside Get Method");
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("Inside Post Method");
PrintWriter out = response.getWriter();
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
/*
* Set the size threshold, above which content will be stored on disk.
*/
fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
/*
* Set the temporary directory to store the uploaded files of size above
* threshold.
*/
fileItemFactory.setRepository(tmpDir);
ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
try {
/*
* Parse the request
*/
List items = uploadHandler.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
/*
* Handle Form Fields.
*/
if (item.isFormField()) {
out.println("File Name = " + item.getFieldName()
+ ", Value = " + item.getString());
} else {
// Handle Uploaded files.
out.println("Field Name = " + item.getFieldName()
+ ", File Name = " + item.getName()
+ ", Content type = " + item.getContentType()
+ ", File Size = " + item.getSize());
}
out.close();
}
} catch (FileUploadException ex) {
log("Error encountered while parsing the request", ex);
} catch (Exception ex) {
log("Error encountered while uploading file", ex);
}
// doGet(request, response);
}
}
In my web.xml, I have
<servlet>
<servlet-name>ImportService</servlet-name>
<servlet-class>com.service.ImportService</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImportService</servlet-name>
<url-pattern>/ImportService/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/jsp/Index.jsp</welcome-file>
</welcome-file-list>
Now when I try to hit the url: http://localhost:8080/delta-webapp/ImportService/jsp/Index.jsp then it gives me blank message and html form is not rendered.
Any suggestions or pointers?
change your entry URL from http://localhost:8080/delta-webapp/ImportService/jsp/Index.jsp
to http://localhost:8080/delta-webapp/jsp/Index.jsp
You've mapped ImportService servlet to handle all requests to /ImportService/*.
Your index.jsp is located at /jsp/Index.jsp. If instead you just put /delta-webapp It /may/ work.
In general though, I don't think welcome files have hard coded paths. Typically you specify something like index.jsp as your welcome file and if nothing handles the request at a particular location, it will fall back to see if one of the welcome files listed is available and will render that.