I had tried to read excel file from jsp to servlet in apache tomcat.
The below code has been receive excel file from apache folder after write the file and get that file.I need to dont write in apache tomcat.How to directly read excel file values.
The following code is MyServletUpload.java .
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
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 javax.servlet.http.HttpSession;
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;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.mysql.jdbc.Statement;
import com.ppts.webwatcher.Validation.Urlvalidation;
import com.ppts.webwatcher.setting.DBConnector;
import com.ppts.webwatcher.webdownload.Webpagedownload;
#WebServlet("/MyservletUpload")
public class MyservletUpload extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String DATA_DIRECTORY = "data";
private static final int MAX_MEMORY_SIZE = 1024 * 1024 * 2;
private static final int MAX_REQUEST_SIZE = 1024 * 1024;
/**
* #see HttpServlet#HttpServlet()
*/
public MyservletUpload() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
int count = 1;
DBConnector db2Connector = DBConnector.getInstance();
Connection con = db2Connector.getConnection(true);
Statement stmt = null;
String compName = null;
String url_Name = null;
String message = null;
if (!isMultipart) {
return;
}
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Sets the size threshold beyond which files are written directly to
// disk.
factory.setSizeThreshold(MAX_MEMORY_SIZE);
// Sets the directory used to temporarily store files that are larger
// than the configured size threshold. We use temporary directory for
// java
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
// constructs the folder where uploaded file will be stored
String uploadFolder = getServletContext().getRealPath("/");
// + File.separator + DATA_DIRECTORY;
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(MAX_REQUEST_SIZE);
try {
// Parse the request
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadFolder + File.separator + fileName;
File uploadedFile = new File(filePath);
System.out.println("file path : " + filePath);
item.write(uploadedFile);
FileInputStream fis = new FileInputStream(uploadedFile);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
// Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
// Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
String h = "";
int i = 1;
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
// Check the cell type and format accordingly
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
break;
case Cell.CELL_TYPE_STRING:
break;
}
if (i == 1) {
h = cell.getStringCellValue();
} else {
h = h + "~" + cell.getStringCellValue();
}
i++;
}
String[] a = h.split("~");
compName = a[0].trim();
url_Name = a[1].trim();
System.out.println("company name : " + compName);
System.out.println("ulr name : " + url_Name);
try {
long ft1 = 0;
long ft2 = 0;
int lk = 0;
BufferedReader in = null;
BufferedWriter be = null;
String filenam = "";
String patr = getServletContext().getRealPath("/");
filenam = patr + "webfolder";
// System.out.println("part : " + filenam);
File filchkr = new File(filenam);
if (filchkr.exists()) {
// System.out.println("fil exists");
} else {
// System.out.println("fil not exists");
}
try {
ft1 = System.currentTimeMillis();
String line1;
// String arrsp =
// "http://www.mmrf.org/research/research.html~helwel131";
int li = compName.length();
// System.out.println("Urlname " + url_Name);
// System.out.println("companyname " +
// compName);
System.out.println("####"
+ Urlvalidation.checkInsertValidation(
url_Name, compName));
if (Urlvalidation.checkInsertValidation(
url_Name, compName) != null) {
System.out
.println("error url name >>>>>>>>> "
+ url_Name);
System.out
.println("errror url link >>>>>>>>>>>"
+ compName);
} else {
String urlreplaceText = url_Name.replace(
" ", "%20");
// System.out.println("path : "+getServletContext().getRealPath("/"));
URL url1 = new URL(urlreplaceText);
// System.out.println(url1);
String filepath = filenam + "/" + compName;
File f1 = new File(filepath);
if (!f1.exists()) {
}
boolean result = false;
try {
f1.mkdir();
result = true;
} catch (SecurityException se) {
// handle it
}
String fullpath = filepath
+ "/firstdownload.html";
Webpagedownload.webdown(fullpath, url1);
lk = 1;
ft2 = System.currentTimeMillis();
long ft = ft2 - ft1;
// System.out.println(ft + ": time ");
String selection = "full_content";
java.util.Date now = new java.util.Date();
String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(
DATE_FORMAT);
String strDateNew = sdf.format(now);
stmt = (Statement) con.createStatement();
String sql = "INSERT INTO new_table (title,url,source_selection,content,inserttime,insertvalue) VALUES ('"
+ compName
+ "','"
+ url_Name
+ "','"
+ selection
+ "','','"
+ strDateNew + "','" + '0' + "')";
stmt.executeUpdate(sql);
HttpSession session = request.getSession();
String username = String.valueOf(session
.getAttribute("username"));
String userid = String.valueOf(session
.getAttribute("userid"));
stmt.executeUpdate("insert into usersession(userid,username,createtime,urlname,urllink) values('"
+ userid
+ "','"
+ username
+ "','"
+ strDateNew
+ "','"
+ compName
+ "','" + url_Name + "')");
}
} catch (Exception e) {
System.out.println("Error: \t" + e);
System.out
.println("exception Urlname>>>>>>>>> "
+ url_Name);
System.out
.println("exception companyname >>>>>>>>>>>"
+ compName);
}
} catch (Exception e) {
System.out.println(e);
}
count++;
}
message = "success";
File file = new File(filePath);
file.delete();
}
}
getServletContext().getRequestDispatcher("/Message.jsp").forward(
request, response);
} catch (FileUploadException ex) {
throw new ServletException(ex);
} catch (Exception ex) {
throw new ServletException(ex);
}
}
}
jsp
<form method="post" action="MyservletUpload"
enctype="multipart/form-data">
Choose File : <input type="file" name="photo" size="50" /> <input
type="submit" value="Upload" onclick="uppload()">
</form>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*,java.util.*,java.io.*"%>
<%# page import="com.ppts.webwatcher.setting.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
function Pager(tableName, itemsPerPage) {
this.tableName = tableName;
this.itemsPerPage = itemsPerPage;
this.currentPage = 1;
this.pages = 0;
this.inited = false;
this.showRecords = function(from, to) {
var rows = document.getElementById(tableName).rows;
// i starts from 1 to skip table header row
for (var i = 1; i < rows.length; i++) {
if (i < from || i > to)
rows[i].style.display = 'none';
else
rows[i].style.display = '';
}
}
this.showPage = function(pageNumber) {
if (! this.inited) {
alert("not inited");
return;
}
var oldPageAnchor = document.getElementById('pg'+this.currentPage);
oldPageAnchor.className = 'pg-normal';
this.currentPage = pageNumber;
var newPageAnchor = document.getElementById('pg'+this.currentPage);
newPageAnchor.className = 'pg-selected';
var from = (pageNumber - 1) * itemsPerPage + 1;
var to = from + itemsPerPage - 1;
this.showRecords(from, to);
}
this.prev = function() {
if (this.currentPage > 1)
this.showPage(this.currentPage - 1);
}
this.next = function() {
if (this.currentPage < this.pages) {
this.showPage(this.currentPage + 1);
}
}
this.init = function() {
var rows = document.getElementById(tableName).rows;
var records = (rows.length - 1);
this.pages = Math.ceil(records / itemsPerPage);
this.inited = true;
}
this.showPageNav = function(pagerName, positionId) {
if (! this.inited) {
alert("not inited");
return;
}
var element = document.getElementById(positionId);
var pagerHtml = '<span onclick="' + pagerName + '.prev();" class="pg-normal"> « Prev </span> ';
for (var page = 1; page <= this.pages; page++)
pagerHtml += '<span id="pg' + page + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + page + ');">' + page + '</span> ';
pagerHtml += '<span onclick="'+pagerName+'.next();" class="pg-normal"> Next »</span>';
element.innerHTML = pagerHtml;
}
}
</script>
<SCRIPT language="javascript">
$(function(){
// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function(){
if($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
});
});
</SCRIPT>
<style>
.textbox {
background:
url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAABClpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wUmlnaHRzPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvcmlnaHRzLyIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iIHhtbG5zOnhtcE1NPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvbW0vIiB4bWxuczpzdFJlZj0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlUmVmIyIgeG1wUmlnaHRzOk1hcmtlZD0iVHJ1ZSIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ1M1IFdpbmRvd3MiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6NzI3NTdDRTExNUFCMTFFMUE5NURCRkMwMEFDNjhEQUMiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6NzI3NTdDRTIxNUFCMTFFMUE5NURCRkMwMEFDNjhEQUMiPiA8ZGM6cmlnaHRzPiA8cmRmOkFsdD4gPHJkZjpsaSB4bWw6bGFuZz0ieC1kZWZhdWx0Ij5DcmVhdGl2ZSBDb21tb25zIEF0dHJpYnV0aW9uIE5vbi1Db21tZXJjaWFsIE5vIERlcml2YXRpdmVzPC9yZGY6bGk+IDwvcmRmOkFsdD4gPC9kYzpyaWdodHM+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOjcyNzU3Q0RGMTVBQjExRTFBOTVEQkZDMDBBQzY4REFDIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOjcyNzU3Q0UwMTVBQjExRTFBOTVEQkZDMDBBQzY4REFDIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+SoKR9AAAAH5JREFUeNpi/P//PwMlgImBQsDS39/fAKTrydTfyESBZhCoR/bCAig9AYgZceAFaGpRwiARKlEAxPOx2AYSS4CqSYSHAZoimEQCGh+rZmwGYDOEAZdmXAZgMwSrZnwGMKBpSMSZDghEUyLtUyIS+z+5eaGRAgc0Mg54bgQIMAAD7RsCMDpK7QAAAABJRU5ErkJggg==)
no-repeat 10px 4px #FFF;
height: 25px;
width: 275px;
border: 1px solid #848484;
padding-left: 30px;
}
</style>
<title>UPDATE SCANNER-Updated Url</title>
</head>
<%# include file="header.jsp"%>
<body>
<SCRIPT language="JavaScript">
function OnSubmitForm()
{
if(document.pressed == 'Send Email')
{
document.myform.action ="emailaction.jsp";
}
else
if(document.pressed == 'View')
{
var slvals = [];
$('input:checkbox[name=case]:checked').each(function() {
slvals.push($(this).val());
});
var i;
for (i = 0; i < slvals.length; i++) {
var url="Multitabhelp.jsp?urlid="+slvals[i];
var win = window.open(url, '_blank');
win.focus();
}
return false;
}
return true;
}
</SCRIPT>
<center>
<b><h1>Updated URL</h1> </b>
<FORM name="myform" onSubmit="return OnSubmitForm();">
<%
int co = 1;
DBConnector db2Connector = DBConnector.getInstance();
Connection conn = db2Connector.getConnection(false);
Statement stmt = null;
Statement stmt1 = null;
String time;
String urld = request.getParameter("urlid");
System.out.println("hello " + urld);
try {
stmt = conn.createStatement();
stmt1 = conn.createStatement();
String son = "";
String b = "";
String sww = "select * from updatehistory where updatetime='"
+ urld + "' and updation='1'";
System.out.println(sww);
ResultSet rs = stmt
.executeQuery("select * from updatehistory where updatetime='"
+ urld + "' and updation='1'");
out.println("<div class='CSSTableGenerator'>");
out.println("<TABLE BORDER=1 id=\"tablepaging\" class=\"yui\" align=\"center\">");
out.println("<th>"
+ " S.No"
+ "</th>");
out.println("<th>"
+ " Date"
+ "</th>");
out.println("<th>"
+ " Source Name"
+ "</th>");
out.println("<th>"
+ " URL"
+ "</th>");
out.println("<th>"
+ " Updated Content"
+ "</th>");
%>
<th><input type="checkbox" id="selectall" /></th>
<%
out.println("<th>"
+ " <label class='col-md-3 control-label'> Action</label>"
+ "</th>");
while (rs.next()) {
time = rs.getString("date_time");
ResultSet rs11 = stmt1
.executeQuery("select * from new_table where urlid='"
+ rs.getString("urlid") + "' ");
if (rs11.next()) {
System.out.println(rs11.getInt(1));
out.println("<TR>");
out.println("<TD>" + co + "</TD>");
out.println("<TD>" + rs.getString("date_time")
+ "</TD>");
out.println("<TD>" + rs11.getString("title")
+ "</a></TD>");
out.println("<TD>" + rs11.getString("url")
+ "</a></TD>");
out.println("<TD>" + rs11.getString("updatecontent")
+ "</a></TD>");
%>
<td><input type="checkbox" class="case" name="case" id="chease"
value="<%=rs.getString("urlid")%>"></td>
<%
out.println("<TD><a href=\"Showupdate.jsp?urlid="
+ rs.getString("urlid") + "\" >VIEW </a></TD>");
}
%>
<%
out.println("</TD>");
out.println("</TR>");
co++;
}
out.println("</TABLE>");
if (co < 2) {
System.out.println("************" + co);
out.println("<center> NO UPDATES </center>");
}
out.print("</div");
} finally {
try {
conn.close();
} catch (SQLException se) {
}
}
%>
<br> Enter Email ID : <input type="text" class="textbox"
name="email"> <INPUT TYPE="SUBMIT" name="Operation"
onClick="document.pressed=this.value" VALUE="Send Email"> <br>
<br> <br> Click to View Selected Update Link... <INPUT
TYPE="SUBMIT" name="Operation" onClick="document.pressed=this.value"
VALUE="View">
</FORM>
<br> <br>
<div id="pageNavPosition" style="padding-top: 20px" align="center">
</div>
<br>
</center>
<script type="text/javascript"><!--
var pager = new Pager('tablepaging', 10);
pager.init();
pager.showPageNav('pager', 'pageNavPosition');
pager.showPage(1);
</script>
<%# include file="footer.jsp"%>
</body>
</html>
Better to use Apache POI and do one thing if you are not using maven download the below jars and keep it in your lib
dom4j-1.6.1.jar,
poi-3.9-20121203.jar,
poi-ooxml-3.9-20121203.jar,
poi-ooxml-schemas-3.9-20121203.jar,
xmlbeans-2.3.0.jar
and then using some classes you can read excel file even a row wise or cell wise
Try this I Hope this will you.....
Hope this helps`
public class ReadExcelfile {
public static void main(String[] args) throws Exception {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Statement stmt = DriverManager.getConnection("jdbc:odbc:employee").createStatement();
ResultSet rs = stmt
.executeQuery("select lastname, firstname, id from [Sheet1$]");
while (rs.next()) {
String lname = rs.getString(1);
String fname = rs.getString(2);
int id = rs.getInt(3);
System.out.println(fname + " " + lname + " id : " + id);
}
rs.close();
stmt.close();
}
}
`
Related
I know that maybe it can be a duplicated question, i read similar post on internet, but i cannot send my input value from jsp to servlet.
I can upload file but i need to send an input value.
Servlet:
try {
FileItemIterator iterator = upload.getItemIterator(req);
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
InputStream in = item.openStream();
if (item.isFormField()) {
out.println("Got a form field: " + item.getFieldName());
} else {
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
String fileNameWithOutExt = FilenameUtils.removeExtension(fileName);
out.println("--------------");
out.println("fileName = " + fileName);
out.println("Kind = " + fileNameWithOutExt);
out.println("field name = " + fieldName);
out.println("contentType = " + contentType);
String fileContents = null;
try {
fileContents = IOUtils.toString(in);
out.println("lenght: " + fileContents.length());
String[] content = fileContents.split("\n");
String[] property = content[0].split(",");
out.println("lunghezza " + property.length);
for (String propr : property) {
out.println("prop: " + propr);
}
//out.println(Arrays.toString(property));
//out.println(fileContents);
} finally {
IOUtils.closeQuietly(in);
}
}
}
} catch (SizeLimitExceededException e) {
out.println("You exceeded the maximu size ("
+ e.getPermittedSize() + ") of the file ("
+ e.getActualSize() + ")");
}
} catch (Exception ex) {
throw new ServletException(ex);
}
}
And that's my jsp
<form action="/upload_kind" method="post" enctype="multipart/form-data" >
<input type="file" name="file" size="50" />
<input type="text" name="namespace" id="namespace">
<br />
<input type="submit" value="Upload File" />
</form>
I read about a "item.getString()" method but it's in DiskFileItem class and not in FileItemStream, so i can see that "namespace" is sent, but i cannot see its value.
Thx and sorry for my bad english
Following the duplicated link, i was able to resolve my problem. I used this code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List<FileItem> 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 e) {
throw new ServletException("Cannot parse multipart request.", e);
}
// ...
}
I've been handed a task to update old code to use Google Custom Site Search. Code below.
The form seems to be working about 95%, But I'm running into an issue when a search is performed I'm getting an "java.lang.ArrayIndexOutOfBoundsException" error.
It seems that some search queries work and other do not.
For Example I run a search using "Hurricane" I'll get the above error. But let's say I search "Hurricane Matthew" it will return x amount of results.
I expect it has to do with line 29 (Notepadd++) of the code
int maxNumReturned = 1000;
along with this line 161
&start + (expectedResultCount - resultsPerPage)
When a serach is performed successfully I'm able to get all the print line to display (Spot 1, spot 1.2 exc to 3.1)
When a search fails it is breaking at Println 3 and not printing out 3.1
looking for some help to be pointed in the right direction, keep in mind that this is very old code
Error that is printed out:
spot 1 spot 1.1 spot 1.2 spot 2 spot 3 757 The page you are trying to view is unavailable. Please try again later
java.lang.ArrayIndexOutOfBoundsException
See code below:
<%
String searchURI = request.getQueryString();
String requestTemp = request.getParameter("num");
requestTemp = stripXSS(encodeHTML(requestTemp));
String query = request.getParameter("q");
query = encodeHTML(query);
String client = request.getParameter("client");
int ud = 1;
query = stripXSS(query);
// Get encoded query
int queryPos = searchURI.indexOf("&q=");
queryPos = queryPos + 3;
String subQuery = searchURI.substring(queryPos);
int j = subQuery.indexOf('&');
if ( j > -1) // Found
subQuery = subQuery.substring(0, j);
String site = request.getParameter("site");
site = encodeHTML(site);
String keyword = "null:" + query;
String resultCount="zero";
int resultsPerPage = 5;
try{
resultsPerPage = Integer.parseInt(request.getParameter("num"));
} catch(Exception e) {
}
int maxNumReturned = 1000;
int PageNo= 0;
int NextPage=0;
int PrevPage=0;
boolean sortByRelevance=true;
String previous = "";
String next = "";
String currentPage ="";
String resultsFrom="";
int total = 0;
int totalPages = 0;
int startResults = 0;
requestTemp = request.getParameter("start");
requestTemp = encodeHTML(requestTemp);
if (requestTemp == null) {
startResults = 0;
} else {
startResults = Integer.parseInt(requestTemp);
if (startResults == 1){
startResults = 0;
}
}
int fromRequest = searchURI.indexOf("?status=RMI1");
if (fromRequest >=0){
searchURI = searchURI.substring(0,fromRequest);
}
int fromRequestQuery = query.indexOf("?status=RMI1");
if (fromRequestQuery >=0) {
query = query.substring(0,fromRequestQuery);
}
if (site == null) {
site = "www.test.com";
}
PageNo = startResults;
String runSearch = request.getParameter("OPN");
%>
<form name="searchform" action="?" method="get" id="searchpg">
<input type="hidden" name="output" value="xml_no_dtd">
<input type="hidden" name="sort" value="date:D:L:d1">
<input type="hidden" name="client" value="google-csbe"> <!-- default_frontend -->
<input type="hidden" name="ud" value="1">
<input type="hidden" name="oe" value="UTF-8">
<input type="hidden" name="ie" value="UTF-8">
<input type="hidden" name="OPN" value="RT1">
<input type="hidden" name="num" value="<%=resultsPerPage%>">
<input type="hidden" name="start" value="0">
<input type="hidden" name="site" value="<%=site%>">
<input type="hidden" name="cx" value="&cx=00100000009622659069:xxxxxx_xxxx">
<span class="search_area">
<input type="text" id="q" name="q" class="txtbox" />
<input type="image" src="/siteImages//searchresults_submit.gif" alt="Submit" id="searchpg_submit" />
</span>
</form>
<%!
public String KWMatch(Node node) {
Node childNode = node.getFirstChild();
String docURI = "";
String GD = null;
String docTitle = null;
String docDesc = "";
while(childNode != null) {
//print link
String nodeName = childNode.getNodeName();
if (nodeName.equals("GL")){
docURI = childNode.getFirstChild().getNodeValue();
}else if (nodeName.equals("GD")){
GD = childNode.getFirstChild().getNodeValue();
if (GD.indexOf("|") > -1) {
docTitle = GD.substring(0, GD.indexOf("|"));
docDesc = GD.substring(GD.indexOf("|")+1, GD.length());
} else {
docTitle = GD;
}
}
childNode = childNode.getNextSibling();
}
//Begin 'search_res' div to hold one search result listing
return("<div class=\"search_res\">" + docTitle + "<p>" + docDesc + "</p></div>");
}
%>
<%
try {
if ("RT1".equals(runSearch)){
out.println("spot 1");
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
URL url = new URL("http://xx.xxx.xxx.xx:5454/test/search?" + searchURI);
URLConnection conn = url.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
Document searchDoc = docBuilder.parse(conn.getInputStream());
out.println("spot 1.1");
Element searchElements = searchDoc.getDocumentElement();
NodeList resultsList = searchElements.getElementsByTagName("R");
NodeList resultsCount = searchElements.getElementsByTagName("M");
NodeList keymatchCount = searchElements.getElementsByTagName("GM");
out.println("spot 1.2");
String preNext = "";
out.println("spot 2");
if(resultsCount.getLength() <= 0 && keymatchCount.getLength() > 0){
out.print("<h2 class=\"searchpage\">" + keymatchCount.getLength() + " results found for " + query + "</h2>");
for(int i=0; i<keymatchCount.getLength(); i++) {
Node node = keymatchCount.item(i);
out.print(KWMatch(node));
}
} else if(resultsCount.getLength() > 0){
Node totalNode = resultsCount.item(0);
int expectedResultCount = Integer.parseInt(totalNode.getFirstChild().getNodeValue()) + (int) keymatchCount.getLength();
if (expectedResultCount > maxNumReturned){
expectedResultCount = maxNumReturned;
}
// String encodedQuery = java.net.URLEncoder.encode(query);
String encodedQuery = subQuery;
String googleQuery = "q=" + encodedQuery + "&output=xml_no_dtd" + "&sort=" + "date:D:S:d1" + "&client=" + client + "&ud=" + ud + "&oe=UTF-8" + "&ie=UTF-8"
+ "&site=" + site + "&start=" + (expectedResultCount - resultsPerPage) + "&num=" + resultsPerPage + "&cx=00100000009622659069:xxxxxx_xxxx";
URL subUrl = new URL("http://xx.xxx.xxx.xx:5454/test/search?" + googleQuery);
URLConnection subConn = subUrl.openConnection();
subConn.setConnectTimeout(10000);
subConn.setReadTimeout(10000);
Document gSearchDoc = docBuilder.parse(subConn.getInputStream());
Element gSearchElements = gSearchDoc.getDocumentElement();
NodeList gResultsList = gSearchElements.getElementsByTagName("R");
out.println("spot 3");
Node lastResultNode = gResultsList.item(gResultsList.getLength() -1);
out.println("spot 3.1");
String lastResultNum = lastResultNode.getAttributes().getNamedItem("N").getNodeValue();
total = Integer.parseInt(lastResultNum) + keymatchCount.getLength();
keyword = query;
resultCount=String.valueOf(total);
Node firstNode =resultsList.item(0);
Node lastNode = resultsList.item(resultsList.getLength()-1);
String firstResultNum = firstNode.getAttributes().getNamedItem("N").getNodeValue();
lastResultNum= lastNode.getAttributes().getNamedItem("N").getNodeValue();
//Node totalNode = resultsCount.item(0);
//total = Integer.parseInt(totalNode.getFirstChild().getNodeValue());
totalPages = (total/resultsPerPage)+1;
startResults = startResults/resultsPerPage;
out.println("spot 4");
out.println(site);
out.print("<h2 class=\"searchpage\">" + total + " results found for \"" + query + "\"</h2>");
if(keymatchCount.getLength() > 0 && startResults == 0){
for(int i=0; i<keymatchCount.getLength(); i++) {
Node node = keymatchCount.item(i);
out.print(KWMatch(node));
}
}
if(startResults == 0 || total <= resultsPerPage){
NextPage=(PageNo/resultsPerPage) +1;
PrevPage = 0;
if (total <= resultsPerPage) {
next= "";
resultsFrom = "";
} else {
next= "<a href='javascript:NextValues()'><img src='/siteImages/page_right.gif' width='5' height='10' /></a>";
//resultsFrom = (1+ PageNo) + " - " + (PageNo + resultsPerPage) + " of " + total;
resultsFrom = firstResultNum + " - " + lastResultNum + " of " + total;
}
previous = "";
} else if(startResults==(totalPages -1)) {
NextPage=(PageNo/resultsPerPage) +1;
PrevPage =(PageNo/resultsPerPage)-1;
//resultsFrom = "1 - " + (PageNo + resultsPerPage) + " of " + total;
resultsFrom = firstResultNum + " - " + lastResultNum + " of " + total;
next = "";
previous= "<a href='javascript:PrevValues()'><img src='/siteImages/page_left.gif' width='5' height='10' /></a>";
} else {
NextPage=(PageNo/resultsPerPage) +1;
PrevPage =(PageNo/resultsPerPage)-1;
//resultsFrom = (1 + PageNo) + " - " + (PageNo + resultsPerPage) + " of " + total;
resultsFrom = firstResultNum + " - " + lastResultNum + " of " + total;
next= "<a href='javascript:NextValues()'><img src='/siteImages/page_right.gif' width='5' height='10' /></a>";
previous= "<a href='javascript:PrevValues()'><img src='/siteImages/page_left.gif' width='5' height='10' /></a>";
}
} else {
out.print("<h2 class=\"searchpage\">No Results Found results found for \"" + query + "\"</h2>");
}
try{
for(int i=0; i< resultsList.getLength(); i++) {
Node node = resultsList.item(i);
Node childNode = node.getFirstChild();
String docURI = "";
String docTitle = null;
String docDesc = "";
while(childNode != null) {
//print link
String nodeName = childNode.getNodeName();
if (nodeName.equals("U")) {
docURI = childNode.getFirstChild().getNodeValue();
} else if (nodeName.equals("T")) {
docTitle = childNode.getFirstChild().getNodeValue();
} else if (nodeName.equals("S")) {
try{
docDesc = childNode.getFirstChild().getNodeValue();
}catch(Exception e){}
} else { }
childNode = childNode.getNextSibling();
}
%>
<!-- Begin 'search_res' div to hold one search result listing -->
<div class="search_res"> <%=docTitle%>
<p><%=docDesc%></p>
</div>
<%
}
}catch(Exception e){
}
}
} catch (Exception e) {
out.println("The page you are trying to view is unavailable. Please try again later");
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
out.println("" + sw.toString());
}
%>
i made a program in java that it takes an excel file and store its data in a database. When i state where the file is its like this:
String filename = "test5.xls";
String path = "C:\\Users\\myfiles\\Documents\\";
But when i call the create table and i state the filename of the excel file because it it test.xls the mysql command shows error!
The create table function is:
try
{
String all = org.apache.commons.lang3.StringUtils.join(allFields, ",");
String createTableStr = "CREATE TABLE " + "table5" + " (" + all + ")";
System.out.println( "Create a new table in the database" );
stmt.executeUpdate( createTableStr );
Is there any way to rename the file before i create the table or to read only the "test" without the .xls?
My program is the below:
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class readexcel {
public static void main (String[] args) throws Exception {
//String filename = "C:\\Users\\myfiles\\Documents\\test5.xls";
String filename = "test5.xls";
String path = "C:\\Users\\myfiles\\Documents\\";
List sheetData = new ArrayList();
FileInputStream fis = null;
try {
fis = new FileInputStream(path + filename);
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(0);
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
HSSFRow row = (HSSFRow) rows.next();
Iterator cells = row.cellIterator();
List data = new ArrayList();
while (cells.hasNext()) {
HSSFCell cell = (HSSFCell) cells.next();
data.add(cell);
}
sheetData.add(data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
}
showExcelData(sheetData);
HashMap<String,Integer> tFields = new HashMap();
tFields = parseExcelData(sheetData);
String str = getCreateTable(filename, tFields);
}
private static void showExcelData(List sheetData) {
// HashMap<String, String> tableFields = new HashMap();
for (int i=0; i<sheetData.size();i++){
List list = (List) sheetData.get(i);
for (int j=0; j<list.size(); j++){
Cell cell = (Cell) list.get(j);
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue());
}
else if(cell.getCellType()==Cell.CELL_TYPE_STRING)
{
System.out.print(cell.getRichStringCellValue());
}
else if(cell.getCellType()==Cell.CELL_TYPE_BOOLEAN) {
System.out.print(cell.getBooleanCellValue());
}
if (j < list.size() - 1)
{
System.out.print(", ");
}
}
System.out.println("");
}
}
#SuppressWarnings({ "unchecked", "unused" })
private static HashMap parseExcelData (List sheetData){
HashMap<String,Integer> tableFields = new HashMap();
List list = (List) sheetData.get(0);
for (int j=0; j<list.size(); j++){
Cell cell=(Cell) list.get(j);
tableFields.put(cell.getStringCellValue(),cell.getCellType());
}
return tableFields;
}
private static String getCreateTable(String tablename, HashMap<String, Integer> tableFields){
Iterator iter = tableFields.keySet().iterator();
String str="";
String[] allFields = new String[tableFields.size()];
int i = 0;
while (iter.hasNext()){
String fieldName = (String) iter.next();
Integer fieldType=(Integer)tableFields.get(fieldName);
switch (fieldType){
case Cell.CELL_TYPE_NUMERIC:
str=fieldName + " INTEGER";
break;
case Cell.CELL_TYPE_STRING:
str= fieldName + " VARCHAR(255)";
break;
case Cell.CELL_TYPE_BOOLEAN:
str=fieldName + " INTEGER";
break;
}
allFields[i++]= str;
}
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/kainourgia","root", "root");
Statement stmt = con.createStatement();
try
{
System.out.println( "Use the database..." );
stmt.executeUpdate( "USE kainourgia;" );
}
catch( SQLException e )
{
System.out.println( "SQLException: " + e.getMessage() );
System.out.println( "SQLState: " + e.getSQLState() );
System.out.println( "VendorError: " + e.getErrorCode() );
}
try
{
String all = org.apache.commons.lang3.StringUtils.join(allFields, ",");
String createTableStr = "CREATE TABLE " + "table5.xls" + " (" + all + ")";
System.out.println( "Create a new table in the database" );
stmt.executeUpdate( createTableStr );
}
catch( SQLException e )
{
System.out.println( "SQLException: " + e.getMessage() );
System.out.println( "SQLState: " + e.getSQLState() );
System.out.println( "VendorError: " + e.getErrorCode() );
}
}
catch( Exception e )
{
System.out.println( ((SQLException) e).getSQLState() );
System.out.println( e.getMessage() );
e.printStackTrace();
}
return str;
}
#SuppressWarnings({ "unused", "unused", "unused", "unused" })
private Statement createStatement() {
return null;
}
}
Thank you in advance!
Gives name of the file
String filename = "test5.xls";
String path = "C:\\Users\\myfiles\\Documents\\";
File f = new File (path + filename);
System.out.println(f.getName());// gives only file name with out extension
I can upload a file in a servlet using the apache commons FileUpload. The code below worked in the processRequest method off the servlet, but I copy Pasted the code in the doPost method and now it doesn't work anymore. the line
List fileItems = upload.parseRequest(request);
makes an empty array of fileItems.
How can this be?
Here is the full doPost method
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int fileId = 0;
String LogicalName = "";
String PartNr = "";
String Cost = "";
String Assembly = "";
String Comment = "";
try {
Connection conn = MysqlConnect.conn();
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) { //als het een veld is dan dit, anders File uploaden
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
switch (fieldname) {
case "logicalName":
LogicalName = fieldvalue;
break;
case "partNr":
PartNr = fieldvalue;
break;
case "cost":
Cost = fieldvalue;
break;
case "assembly":
Assembly = fieldvalue;
break;
case "comments":
Comment = fieldvalue;
break;
}
} else {
PrintWriter out = response.getWriter();
File file;
int maxFileSize = 500000 * 1024;//max 500 mb groot
int maxMemSize = 5000 * 1024;//max 5mb gecached in het ram,indien file groter is eerst wegschrijven in een temp dir
String filePath = "C:\\uploads\\";
String fileName = "";
String contentType = request.getContentType();
if ((contentType.indexOf("multipart/form-data") >= 0)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(maxMemSize);
factory.setRepository(new File("c:\\temp"));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxFileSize);
try {
List fileItems = upload.parseRequest(request);
Iterator i = fileItems.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (!fi.isFormField()) {
String fieldName = fi.getFieldName();
fileName = fi.getName();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
if (fileName.lastIndexOf("\\") >= 0) {
file = new File(filePath
+ fileName.substring(fileName.lastIndexOf("\\")));
} else {
file = new File(filePath
+ fileName.substring(fileName.lastIndexOf("\\") + 1));
}
fi.write(file);
}
}
HttpSession session = request.getSession();
int uploader = (Integer) session.getAttribute("UserId");
String Query = "Insert into tbl_file (fileLocation,Uploader)values(\"" + fileName + "\"," + uploader + ");";
PreparedStatement st = conn.prepareStatement(Query, Statement.RETURN_GENERATED_KEYS);
st.executeUpdate();
ResultSet rs = st.getGeneratedKeys();
if (rs.next()) {
fileId = rs.getInt(1);
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
}
if (fileId == 0) {
//ERROR
} else {
Statement stmt = conn.createStatement();
String Query1 = "Insert into tbl_part (partCad,partCost,partAssembly,partMotivation,partOf) VALUES(" + fileId + "," + Cost + "," + Assembly + ",\"" + Comment + "\"," + "1" + ");";
stmt.executeUpdate(Query1);
}
MysqlConnect.close(conn);
} catch (SQLException ex) {
Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
}
String URL = "/home.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(URL);
dispatcher.forward(request, response);
}
And This is the JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="/Racing/UploadServlet" method="post"
enctype="multipart/form-data">
<input type="file" name="file" />
<br />
Logische Naam: <input type="text" name="logicalName"><br>
Stuknr(automatisch,nog niet geimplementeerd): <input type="text" name="partNr"><br>
Kost: <input type="text" name="cost"><br>
Assembly:
<select name = "assembly">
<c:forEach var ="assembly" items="${Assemblys}">
<option value="${assembly.id}">${assembly.name}</option>
</c:forEach>
</select>
<br>
<textarea name="comments" cols="25" rows="5">
Verdediging Design
</textarea><br>
<input type="submit" value="Upload File" />
</form>
</body>
</html>
Many thanks in advance!
Your code line List fileItems = upload.parseRequest(request); and even all the lines in the else part doesn't have any sense at all because:
You already have processed the request before in this line
List<FileItem> items = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
No need to process the request again.
You already have the file you want/need to process in the item object which isFormField method returns false.
Change your method in order to look like here: How to upload files to server using JSP/Servlet?:
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) { //als het een veld is dan dit, anders File uploaden
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
switch (fieldname) {
case "logicalName":
LogicalName = fieldvalue;
break;
//other case statements...
}
} else {
//here you only have to process the file
File file;
int maxFileSize = 500000 * 1024;//your comments...
int maxMemSize = 5000 * 1024;//your comments...
//this must be a constant or a servlet init param, do not hard code it
String filePath = "C:\\uploads\\";
String fileName = FilenameUtils.getName(item.getName());
factory.setSizeThreshold(maxMemSize);
//didn't you have a filePath variable?
factory.setRepository(new File("c:\\temp"));
upload.setSizeMax(maxFileSize);
try {
String fieldName = fi.getFieldName();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
file = new File(filePath, fileName);
item.write(file);
//code to save your file location in db...
//note: this MUST BE in a business logic method, not directly written in your servlet
HttpSession session = request.getSession();
int uploader = (Integer) session.getAttribute("UserId");
} catch (Exception ex) {
//very BAD idea
//use a logger instead like log4j or sfl4j
System.out.println(ex);
}
}
}
Additional: check the File(String parent, String child) constructor.
Is it possible to have AJAX output to html, rather than plain-text?
I have a file that pulls a class result from an SQL database. The database connection works, and it prints, but rather than printing the table format I desire, it simply prints the table elements as text on the page instead.
public class hw11
{
int crn;
String output = "temp";
public String getOfferings(int crn)
{
this.crn = crn;
//DB Connection
String url = "jdbc:odbc:registrar";
Connection con;
PreparedStatement stmt;
String query;
query = "SELECT * FROM offerings WHERE crn = " + crn +";";
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(java.lang.ClassNotFoundException e)
{
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try
{
con = DriverManager.getConnection(url, "", "");
stmt = con.prepareStatement(query);
ResultSet rs = stmt.executeQuery();
output = "<table border='1'><tr>";
output+= "<th>CRN</th><th>Course</th><th>Section</th><th>Dates</th><th>Times</th><th>Instructor</th><th>Room</th><th>Max Enrolled</th><th>Current Enrolled</th></tr>";
while (rs.next())
{
String course = rs.getString("COURSE");
String section = rs.getString("SECTION");
String dates = rs.getString("DATES");
String times = rs.getString("TIMES");
String instructor = rs.getString("INSTRUCTOR");
String room = rs.getString("ROOM");
int enrollmax = rs.getInt("ENROLLMAX");
int enrollcur = rs.getInt("ENROLLCURRENT");
output += "<tr>";
output += "<td>"+crn+"</td><td>";
output += "<td>"+course+"</td><td>";
output += "<td>"+section+"</td><td>";
output += "<td>"+dates+"</td><td>";
output += "<td>"+times+"</td><td>";
output += "<td>"+instructor+"</td><td>";
output += "<td>"+room+"</td><td>";
output += "<td>"+enrollmax+"</td><td>";
output += "<td>"+enrollcur+"</td><td>";
output += "</tr>";
}
output += "</table>";
stmt.close();
con.close();
}
catch (SQLException ex)
{
System.err.println("SQLException: " + ex.getMessage());
}
//Output
return output;
}
}
HTML Page:
<p>
Get Course Offerings
<br/><br/>
Course CRN: <input type="text" id="theCrn"/>
<input value="Send" type="button" onclick="update()"/>
<br/>Reply:<br/>
<span id="theReply"></span>
</p>
Yes, you can return anything in response to an ajax call.
Just make sure you append it properly to the page.