Handling multiple submit buttons with JSP and Servlets - sql

I have a table that is generated from the database. This table will be enclosed in a form. Below is the result on a browser:
http://i.imgur.com/NLZzgwP.png (Low rep problems)
Below is the JSP/JSTL code:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Issues</title>
<style type="text/css">
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
td {
padding: 10px;
}
</style>
</head>
<body>
<sql:setDataSource
var="myDS"
driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/pdfdb"
user="user" password="*******"
/>
<sql:query var="listIssues" dataSource="${myDS}">
SELECT BookId from Book;
</sql:query>
<form method="get" action="fileDownload">
<div align="center">
<table>
<caption>List of Issues</caption>
<tr>
<th>Magazine Issue #</th>
<th>Download</th>
</tr>
<c:forEach var="issue" items="${listIssues.rows}">
<tr>
<td><c:out value="${issue.BookId}" /></td>
<td><input name='<c:out value="${issue.BookId}" />' type="submit" value="Download"></td>
</tr>
</c:forEach>
</table>
</div>
</form>
</body>
</html>
Now, what I want is for the download button to be kind of linked with the id/Issue number that is placed on the same row as the button such that, when the user clicks the download button, it passes the id/magazine issue number to the url telling the browser that the user wants to download the corresponding magazine issue number of that button clicked. Below is the servlet I use to implement this:
package com.mypackage.fileDownload;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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;
/**
* Servlet implementation class FileDownloadServlet
*/
#WebServlet("/fileDownload")
public class FileDownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//size of byte buffer to send file
private static final int BUFFER_SIZE = 4096;
//database connection settings
private String dbUrl = "jdbc:mysql://localhost:3306/pdfdb";
private String dbUser = "user";
private String dbPass = "******";
/**
* #see HttpServlet#doGet(HttpServletRequesrequest,HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//get upload id from URL's parameters
String uploadId = request.getParameter("name");
Connection con = null; //connects to the database
try {
//connects to the database
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(dbUrl, dbUser, dbPass);
//queries the database
String sql = "SELECT * FROM Book WHERE BookId = ?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, uploadId);
ResultSet result = pstmt.executeQuery();
if(result.next()) {
//gets file name and file blob data
String fileId = result.getString("BookId");
Blob blob = result.getBlob("BookContent");
InputStream inputStream = blob.getBinaryStream();
int fileLength = inputStream.available();
System.out.println("File length = " + fileLength);
ServletContext context = getServletContext();
//Sets MIME type for the file download
String mimeType = context.getMimeType(fileId);
if(mimeType == null) {
mimeType = "application/octet-stream";
}
//set content properties and header attributes for the response
response.setContentType(mimeType);
response.setContentLength(fileLength);
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", fileId);
response.setHeader(headerKey, headerValue);
//writes the file to the client
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outStream.close();
} else {
//no file found
response.getWriter().print("File not found for the id: " + uploadId);
}
} catch(SQLException ex) {
ex.printStackTrace();
response.getWriter().print("SQL Error: " + ex.getMessage());
} catch(IOException ex) {
ex.printStackTrace();
response.getWriter().print("IO Error: " + ex.getMessage());
} catch(ClassNotFoundException ex) {
ex.printStackTrace();
response.getWriter().print("Class Missing Error: " + ex.getMessage());
}
finally {
if(con != null) {
//closes the database connection
try {
con.close();
} catch(SQLException ex) {
ex.printStackTrace();
}
}
}
}
}
Well, from the way I have done this, it is not working the way I wanted it to. For example, if you run this code on the server and click any of the download buttons, the url will be something like
issue.jsp?1=Download
which is weird.It will also display on the browser
File not found for the id: null
I expect something like(on the url)
issue.jsp?Download=1
where 1 is the issue being downloaded. My database has two columns: the IssueId and fileContent(content of file stored in BLOB).
I think I have explained enough and the concept is clear. Any help will be appreciated and this is as far as I could go with my code & research. Thanks!

The simplest way is to just move the form inside the table and do multiple forms:
<div align="center">
<table>
<caption>List of Issues</caption>
<tr>
<th>Magazine Issue #</th>
<th>Download</th>
</tr>
<c:forEach var="issue" items="${listIssues.rows}">
<tr>
<td><c:out value="${issue.BookId}" /></td>
<td>
<form method="get" action="fileDownload">
<input type='hidden' name='bookid' value='<c:out value="${issue.BookId}" />' />
<input type="submit" value="Download">
</form>
</td>
</tr>
</c:forEach>
</table>
</div>
You also need to move the value out of the name attribute of the button and into the value attribute of a hidden input. That hidden input needs a name you will use to get the value in the servlet: request.getParameter("bookid");

Related

How to fix NullPointerException when uploading picture in database?

I want to upload a picture in database, and this is my jsp:
<body>
<form action="addbooka" method="POST" enctype="multipart/form-data">
Title:<input type="text" value="${title}" name="title"> <br>
Description: <input type="text" value="${description}" name="description"><br>
Price: <input type="text" value="${price}" name="price"><br>
Picture: <input type="file" name="myimg"><br>
<button type="submit">Add</button>
</form>
</body>
And this is method where i insert picture:
public static void insertImage(String myImage) throws Exception {
try {
String insertImage = ("insert into image(image) values(?)");
PreparedStatement ps = DataBaseConnection.get().prepareStatement(insertImage);
File file = new File(myImage);
InputStream in = new FileInputStream(file);
ps.setBlob(1, in);
ps.executeUpdate();
In servlet i just call this method and pass request.getParameter("myimg") as an argument(input tag).
After some research i think i get this error because i did't put boundary in form tag. But i can't wrap my head around what numbers to put, what to do next or is it really error because of boundary or something else?
In your servlet don't forget to put #MultipartConfig annotation.Also , you are passing string to your method instead that should be Part . i.e :
int row=0;
InputStream inputStream = null; // input stream of the upload file
// obtains the upload file part in this multipart request
Part filePart = request.getPart("myimg");//get image
insertImage(filePart)//pass to method
public static void insertImage(Part filePart) throws Exception {
String insertImage = ("insert into image(image) values(?)");
PreparedStatement ps = DataBaseConnection.get().prepareStatement(insertImage);
if (filePart != null) {
// obtains input stream of the upload file
inputStream = filePart.getInputStream();
}
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
ps.setBlob(1, inputStream);
}
row = ps.executeUpdate();
if (row > 0) {
out.println("done")
}
}

Why session.getAttribute() always returning null inside JSP page textbox?

I am always getting null value in jsp page textbox. I have defined name attribute in index.jsp page and fetching value using <%=session.getAttribute()%>.
Here is index.jsp
<tr>
<td>First Name</td>
<td>
<input type="text" required="" name="firstname" value="<%=session.getAttribute("firstname")%>"/>
</td>
</tr>
In below UploadServletClass.java, session is defined
public class UploadServletClass extends HttpServlet{
PrintWriter out = null;
Connection con = null;
PreparedStatement ps = null;
HttpSession session = null;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
response.setContentType("text/plain;charset=UTF-8");
try{
out = response.getWriter();
session = request.getSession();
...
}
}
}
This is loginScript.jsp
<%
String zfid = request.getParameter("zid");
String fname = request.getParameter("firstname");
...
if (rs.next()) {
session.setAttribute("zfid", zfid); //used ${sessionScope.zfid} to display value into textbox and it is successful.
session.setAttribute("firstname",fname); //failed to display value in textbox
//out.println("welcome " + userid);
//out.println("<a href='logout.jsp'>Log out</a>");
response.sendRedirect("home.jsp");
}

Java Program to View the file Diff

Result.jsp :
<%#page import="org.apache.commons.lang3.StringUtils"%>
<%#page import="java.util.ArrayList"%>
<%#page import="java.util.Iterator"%>
<%#page import="java.util.ArrayList"%>
<%#page import="util.Utility"%>
<%# 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>Insert title here</title>
</head>
<body>
<table cellpadding="3" cellspacing="3" border="3">
<tr>
<th align="center"><b>Current BootConf</b></th>
<th><b>New BootConf</b></th>
</tr>
<%
ArrayList<String> currentHacks = (ArrayList<String>) request.getAttribute("currentHacks");
ArrayList<String> newHacks = (ArrayList<String>) request.getAttribute("newHacks");
int size = currentHacks.size() > newHacks.size() ? currentHacks.size() : newHacks.size();
Iterator<String> current = currentHacks.iterator();
/* String cur[]=new String[currentHacks.size()];
String newBootconf[]=new String[newHacks.size()]; */
String cur[]=new String[size];
String newBootconf[]=new String[size];
int count=0;
while (current.hasNext()) {
cur[count]=(String)current.next();
count++;
}
count=0;
Iterator<String> new_hacks = newHacks.iterator();
while (new_hacks.hasNext()) {
newBootconf[count]=(String)new_hacks.next();
count++;
}
for(int i=0;i<size;i++){ %>
<tr>
<%
if(!Utility.replaceNull(cur[i]).equalsIgnoreCase(Utility.replaceNull(newBootconf[i]))){
%>
<td bgcolor="red"><%= Utility.replaceNull(cur[i])%></td>
<td bgcolor="red"><%= Utility.replaceNull(newBootconf[i])%></td>
<%}else{ %>
<td><%= Utility.replaceNull(cur[i])%></td>
<td><%= Utility.replaceNull(newBootconf[i])%></td>
<%}%>
</tr>
<%}
%>
</table>
</body>
</html>
ServletDiff.java
DoGet Method:
ArrayList<String> currentHacks = readFile(currentFolderPath, hacks);
ArrayList<String> newHacks = readFile(newFolderPath, hacks);
request.setAttribute("currentHacks",currentHacks);
request.setAttribute("newHacks",newHacks);
RequestDispatcher requestDispatcher;
requestDispatcher = request.getRequestDispatcher("/result.jsp");
requestDispatcher.forward(request, response);
**Method to Read File**
public ArrayList<String> readFile(String folderPath, String fileName) {
File f =null;
FileInputStream fis = null;
String line = null;
ArrayList<String> result= new ArrayList<String>();
int count=0;
try {
f=new File(folderPath + "\\" + fileName);
fis = new FileInputStream(f);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
while ((line = br.readLine()) != null) {
result.add(StringEscapeUtils.escapeXml(line));
count++;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}`
Utility Class
public static String replaceNull(String input) {
return input == null ? "" : input;
}

What should I do to upload the file using jsp/servlet and storing in the ms-access db

this is my productregistration.jsp I want to upload the image and want to also send the data to servlet which is ProductRegistartionServlet.java....can you help me? how it can be possible...
I have already added both jar files named as common-io and common-file-upload
<form action="/eauction/ProductRegistrationServlet" ENCTYPE="multipart/form-data" method="post">
<div class="form_row">
<label class="contact"><strong>Product Image:</strong></label>
<input type="file" class="contact_input" required="required" name="file" />
</div>
<div class="form_row">
<label class="contact"><strong>Product Name:</strong></label>
<input type="text" class="contact_input" required="required" name="p_name" />
</div>
<div class="form_row">
<label class="contact"><strong>Product Type:</strong></label>
<input type="text" class="contact_input" name="p_type" />
</div>
<div class="form_row">
<label class="contact"><strong>Product Prize:</strong></label>
<input type="text" class="contact_input" name="p_prize" required="required" />
</div>
<div class="form_row">
<label class="contact"><strong>Product:</strong></label>
<input type="text" class="contact_input" min="8" max="10" name="p_product" required="required" />
</div>
<div class="form_row">
<label class="contact"><strong>Product Details:</strong></label>
<textarea name="p_detail" class="contact_input" size="200"></textarea>
</div>
<p> </p>
<p> </p>
<div class="form_row">
<input type="image" src="images/GoDf5.gif" alt="submit form"/>
</div>
</form>
here is my servlet help me to figure out the problem please
and this is my ProductRegistrationServlet.java
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
/**
*
* #author Samkit
*/
public class ProductRegistrationServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
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)
String p_name =request.getParameter("p_name");
String p_type=request.getParameter("p_type");
String p_prize=request.getParameter("p_prize");
String p_product=request.getParameter("p_product");
String p_detail=request.getParameter("p_detail");
System.out.print(p_name);
} else {
// Process form file field (input type="file").
String fieldname = item.getFieldName();
String filename = FilenameUtils.getName(item.getName());
DataInputStream in = new DataInputStream(item.getInputStream());
// ... (do your job here)
String contentType = request.getContentType();
String saveFile="";
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while(totalBytesRead < formDataLength){
byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
File ff = new File("C:/"+saveFile);
FileOutputStream fileOut = new FileOutputStream(ff);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
}
}
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
}
// ...
}}
/*
Connection con = null;
ResultSet rst = null;
Statement st = null;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:register");
st =con.createStatement();
rst = st.executeQuery("Select * from productregisteration");
int i = st.executeUpdate("INSERT INTO productregisteration VALUES('"+ff.getPath()+"','"+p_name+"','"+p_type+"','"+p_prize+"','"+p_product+"','"+p_detail+"')");
} catch (ClassNotFoundException ex) {
Logger.getLogger(WelcomeServlet.class.getName()).log(Level.SEVERE, null, ex);
} catch(SQLException se){
}
}
}}*/
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
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 org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class ProductRegistrationServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
File savedFile = null;
PrintWriter out = response.getWriter();
String p_name="",p_type="",p_detail="",p_prize="",p_product="",itemName="",User_Name="";
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)
if(fieldname.equals("p_type")){
p_type = fieldvalue;
}
if(fieldname.equals("p_name")){
p_name = fieldvalue;
out.println(p_name);
}
if(fieldname.equals("p_prize")){
p_prize = fieldvalue;
}
if(fieldname.equals("p_product")){
p_product = fieldvalue;
}
if(fieldname.equals("p_detail")){
p_detail = fieldvalue;
}
}
else {
itemName = item.getName();
savedFile = new File("C:\\Users\\Samkit\\Documents\\NetBeansProjects\\eauction\\web\\upload\\"+itemName);
out.println(savedFile);
item.write(savedFile);
}
}
Connection con = null;
ResultSet rst = null;
Statement st = null;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:register");
st=con.createStatement();
//Getting the date only
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
String p_date = dateFormat.format(date);
System.out.println(p_date);
//Getting the time only
Calendar calendar = new GregorianCalendar();
String am_pm;
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";

RichFaces fileupload and h:message problem

I am using RichFaces 4. My problem is that the message does not appear at all. If I use rich:message the message appears briefly then dissapears.
This is the controller:
public void uploadListener(final FileUploadEvent event) throws IOException
{
final UploadedFile item = event.getUploadedFile();
final FacesContext context = FacesContext.getCurrentInstance();
final Application application = context.getApplication();
final String messageBundleName = application.getMessageBundle();
final Locale locale = context.getViewRoot().getLocale();
final ResourceBundle resourceBundle = ResourceBundle.getBundle(messageBundleName, locale);
final String msg = resourceBundle.getString("upload.failed");
final String detailMsgPattern = resourceBundle.getString("upload.failed_detail");
try
{
CSVImporter.doImport(item.getInputStream(), registry, item.getName());
}
catch (ParseException e)
{
final Object[] params = {item.getName(), e.getMessage()};
final String detailMsg = MessageFormat.format(detailMsgPattern, params);
final FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, detailMsg);
context.addMessage("uploadForm:uploader", facesMsg);
}
catch (TokenMgrError e)
{
final Object[] params = {item.getName(), e.getMessage()};
final String detailMsg = MessageFormat.format(detailMsgPattern, params);
final FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, detailMsg);
context.addMessage("uploadForm:uploader", facesMsg);
}
}
And this is the view:
<h:form id="uploadForm" enctype="multipart/form-data">
<h:message id="message" showDetail="true" for="uploader" errorClass="error" warnClass="warning" infoClass="info" fatalClass="fatal"/>
<rich:fileUpload id="uploader"
fileUploadListener="#{itemController.uploadListener}"
maxFilesQuantity="1"
acceptedTypes="csv">
<a4j:ajax event="uploadcomplete" execute="#none" render="items, message" />
</rich:fileUpload>
</h:form>
In both cases Firebug reports an empty message field being sent.
<?xml version='1.0' encoding='UTF-8'?>
<partial-response><changes><update id="uploadForm:message"><![CDATA[<span id="uploadForm:message"></span>]]></update><update id="j_idt16:items"><![CDATA[<table id="j_idt16:items">
<thead>
<tr>
<th scope="col">
Titles
</th>
</tr>
</thead>
<tbody>
<tr><td></td></tr></tbody>
</table>
]]></update><update id="javax.faces.ViewState"><![CDATA[8859542538952100446:6041172679113548382]]></update></changes></partial-response>
The problem was the a4j:ajax tag. It was sending a second request, and the messages were cleared. This works:
<h:form id="uploadForm" enctype="multipart/form-data">
<h:message id="message" showDetail="true" for="uploader" errorClass="error" warnClass="warning" infoClass="info" fatalClass="fatal"/>
<rich:fileUpload id="uploader"
fileUploadListener="#{itemController.uploadListener}"
maxFilesQuantity="1"
acceptedTypes="csv"
render="items, message" />
</h:form>
Rich upload doesn't rerender messages:
https://community.jboss.org/message/55888
https://issues.jboss.org/browse/RF-3566